请教linux下c语言函数fork父进程打印子进程的PID
关注:296答案:2信息版本:手机版
解决时间 -01-14 04:55
雨不眠的下
-01-13 12:23
用于输入:n (在父进程中输入)
输出:从1到n的整数(子进程负责打印)
父进程打印子进程的PID,然后等待子进程结束,最后输出child complete,退出系统
最佳答案
逐風
-01-13 12:37
#include
#include
#include
#include
#include
#include
int main()
{
int pipe_fds[2];
int pid;
if(pipe(pipe_fds))
{
fprintf(stderr,"pipe error!\n");
return -1;
}
if((pid = fork())<0)
{
fprintf(stderr, "fork error!\n");
return -1;
}
if(pid == 0)
{
char buf[20] = {0};
int n,i;
close(pipe_fds[1]);
read(pipe_fds[0],buf,sizeof(buf));
n=atoi(buf);
for(i=1;i<=n;i++)
{
if(i%10 == 0)
printf("\n");
printf("%d\t",i);
}
close(pipe_fds[0]);
}
else
{
int m;
char bf[20] = {0};
close(pipe_fds[0]);
printf("the child pid:%d\n",pid);
printf("please input number:");
scanf("%d",&m);
printf("\n");
sprintf(bf,"%d",m);
write(pipe_fds[1],bf,sizeof(bf));
wait(NULL);
printf("child complete!\n");
}
return 0;
}
全部回答
1楼时间的尘埃
-01-13 14:07
#include
#include
#include
int main()
{
pid_t pid;
char *message;
int n;
pid_t chldpid;
pid_t ppid;
printf("fork program starting\n");
pid = fork();
switch(pid)
{
case -1:
perror("fork failed");
_exit(1);
case 0:
chldpid = getpid();
printf("chldpid = %ld ppid=%ld\n",(unsigned int)chldpid,(unsigned int)getppid());
message = "this is the child";
n = 5;
break;
default:
ppid = getpid();
printf("ppid = %ld ppid=%ld\n",(unsigned int)ppid,(unsigned int)getppid());
message = "this is the parent";
n = 3;
break;
}
for(; n > 0; n--) {
puts(message);
sleep(1);
}
_exit(0);
}
我要举报
如以上问答内容为色情/暴力/低俗/不良/侵权等信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!
大家都在看
推荐资讯