【发布时间】:2016-02-21 16:11:00
【问题描述】:
我必须编写代码来使用父进程创建多个子进程。 父进程应该处于休眠状态,直到它创建进程数。 子进程向父进程发送 SIGCHLD 信号以中断睡眠并强制父进程调用等待终止子进程的状态集合。
我在 UBUNTU 上写了以下代码:
#include <stdlib.h> /* needed to define exit() */
#include <unistd.h> /* needed for fork() and getpid() */
#include <signal.h> /* needed for signal */
#include <stdio.h> /* needed for printf() */
int main(int argc, char **argv)
{
void catch(int); /* signal handler */
void child(int); /* the child calls this */
void parent(int pid); /* the parent calls this */
int pid; /* process ID */
int i; /* Number of processes*/
signal(SIGCHLD, catch); /* detect child termination */
for(i=0;i<5;i++)
{
pid = fork(); /* create child process*/
switch (pid)
{
case -1: /* something went wrong */
perror("fork");
exit(1);
case 0: /* a fork returns 0 to the child */
child(i+1);
break;
default: /* a fork returns a pid to the parent */
//parent(pid);
break;
}
}
exit(0);
}
void child(int id)
{
printf("\tchild%d: I'm the child\n",id);
sleep(10); /* do nothing for 3 seconds */
printf("\tchild: I'm exiting\n");
exit(id); /* exit with a return code of 123 */
}
void parent(int pid)
{
printf("parent: I'm the parent\n");
sleep(15); /* do nothing for five seconds */
printf("parent: exiting\n");
}
void catch(int snum)
{
int pid;
int status;
pid = wait(&status);
printf("parent: child process exited with value %d\n",WEXITSTATUS(status));
/* WEXITSTATUS(status):
* Since only the last 8 bits are available
* it will be logical to mask the upper bit by
* doing a bitwise and operation with 255.
* A system defined macro does this for us.
*/
}
我得到这样的输出:
parent: I'm the parent
child1: I'm the child
child: I'm exiting
parent: child process exited with value 1
parent: exiting
parent: I'm the parent
child2: I'm the child
child: I'm exiting
parent: child process exited with value 2
parent: exiting
parent: I'm the parent
child3: I'm the child
child: I'm exiting
parent: child process exited with value 3
parent: exiting
parent: I'm the parent
child4: I'm the child
child: I'm exiting
parent: child process exited with value 4
parent: exiting
parent: I'm the parent
child5: I'm the child
child: I'm exiting
parent: child process exited with value 5
parent: exiting
而我想要这样的输出:
parent: I'm the parent
child1: I'm the child
child: I'm exiting
parent: child process exited with value 1
child2: I'm the child
child: I'm exiting
parent: child process exited with value 2
child3: I'm the child
child: I'm exiting
parent: child process exited with value 3
child4: I'm the child
child: I'm exiting
parent: child process exited with value 4
child5: I'm the child
child: I'm exiting
parent: child process exited with value 5
parent: exiting
我应该对我的代码进行哪些更改...? 请帮忙..!!!
【问题讨论】:
-
对我来说,这看起来好像输出和源不匹配。
-
我在这里给出了预期的输出和我得到的输出。第一个是我得到的,另一个是我期望的。
-
在你的源代码中你对
parent()的调用被注释掉了。 -
忽略那个 cmets
-
"*you you" 应该读作“you show”或 wtf ... sry ... ;-)