C语言 如何使进程彼此并行创建,而不是一个接一个地创建?



我需要帮助修改这段代码。现在,它创建一个进程,然后等待它的终止。在此之后,创建另一个进程,然后等待它的终止。我想修改它,使它同时创建两个进程,并并行地执行它们。代码是:

#include <sys/types.h>
#include <stdio.h>
int main(int argc, char * argv[]) {
pid_t pid;
int status;
pid = fork();
if (pid != 0) {
while (pid != wait( & status));
} else {
sleep(5);
exit(5);
}
pid = fork();
if (pid != 0) {
while (pid != wait( & status));
} else {
sleep(1);
exit(1);
}
}

应该这样做的代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid != 0)
printf("Child 1 PID = %dn", pid);
else
{
sleep(5);
exit(5);
}
pid = fork();
if (pid != 0)
{
printf("Child 2 PID = %dn", pid);
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child %d exited with status 0x%.4Xn", corpse, status);
}
else
{
sleep(1);
exit(1);
}
return 0;
}

有一次当我运行它时,我得到了输出:

Child 1 PID = 49582
Child 2 PID = 49583
Child 49583 exited with status 0x0100
Child 49582 exited with status 0x0500

如果您愿意,您可以将wait()循环及其变量声明移动到if结构之后,并紧接在末尾的return 0;结构之前。这样会有更好的对称性。您甚至可以将子创建阶段包装成调用两次的函数:

static void procreate(int kidnum, int naptime)
{
int pid = fork();
if (pid != 0)
printf("Child %d PID = %d (nap time = %d)n", kidnum, pid, naptime);
else
{
sleep(naptime);
exit(naptime);
}
}

,然后在main()中,你只需要两次调用procreate()和等待循环:

int main(void)
{
procreate(1, 5);
procreate(2, 1);
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child PID %d exited with status 0x%.4Xn", corpse, status);
return 0;
}

最新更新