When you use fork in C, you must imagine that the process code and state are copied to the new process, after which it starts execution from where it left off.
When you use exec in C, you must imagine that the whole process is replaced if the call succeeds.
, . , .
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t cpid;
pid_t pidChildren[5];
int i;
for (i = 0; i < 5; i++)
{
cpid = fork();
if (cpid < 0) {
printf("fork failed\n");
} else if (cpid == 0) {
printf("fork successful\n");
break;
} else {
pidChildren[i] = cpid;
}
}
if (cpid == 0) {
char *cmd[] = {"ls", "-l", NULL};
if (execvp(cmd[0], cmd) < 0) {
printf("execvp failed\n");
return -1;
}
}
int exitStatus = 0;
for (i = 0; i < 5; i++) {
waitpid(pidChildren[i], &exitStatus, 0);
printf("Child %d exited with status %d\n", i, exitStatus);
}
return 0;
}