I'm a student studying C and how to create processes using fork() Can you please explain what is the difference between these two codes because I've tried the both and they didn't work as expected.
child = fork();
child1 = fork();
if (child == 0 && child1 == 0){//Parent}
else if (child > 0 && child1 == 0){//first child}
else if (child == 0 && child1 > 0){//second child}
else {third child}
is this is the right way to create the children or is it the one below?
child = fork();
if (child == 0)
{
child1 = fork();
if (child1 == 0)
{// grandchild
}
else
{//child
}
}
else
{//parent
}
These are examples written by me on what confused me. Here's the code i'm having trouble with
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char ** argv)
{
pid_t child;
pid_t child1;
// at least, there should be 3 arguments
// 2 for the first command, and the rest for the second command
//printf("%d\n", argc);
if (argc < 4) {
fprintf(stderr, "Usage: %s cmd1 cmd1_arg cmd2 [cmd2_args ..]\n", argv[0]);
return 1;
}
child = fork();
//pid_t child1;
// TODO
if (child < 0)
{
perror("fork()");
exit(EXIT_FAILURE);
}
if (child == 0)//child1
{
//printf("exited=%d exitstatus=%d\n", WIFEXITED(exitStatus), WEXITSTATUS(exitStatus));
child1 = fork();
if (child1 == 0)//grandchild
{
execlp(argv[1],argv[1],argv[2],NULL);
perror("execlp()");
exit(EXIT_FAILURE);
}
else //first child
{
int status1;
waitpid(child1, &status1, 0);
printf("exited=%d exitstatus=%d\n", WIFEXITED(status1), WEXITSTATUS(status1));
execvp(argv[3], (argv + 3));
perror("execlp()");
exit(EXIT_FAILURE);
}
}
else//parent
{
int status;
waitpid(child, &status, 0);
printf("exited=%d exitstatus=%d\n", WIFEXITED(status), WEXITSTATUS(status));
}
return 0;
}
I'm able to get the code to work as intended but i'm confused on how to use WIFEXITED and WEXITSTATUS. My code output when I run this code is
execlp(): No such file or directory
Makefile
exited=1 exitstatus=0
And the right output is:
execlp(): No such file or directory
Makefile
exited=1 exitstatus=1
exited=1 exitstatus=0
Arguments used in this test case
cal -3 ls Makefile
Why am I missing the second exit print?