1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > linux父进程中显示子进程pid 请教linux下c语言函数fork父进程打印子进程的PID

linux父进程中显示子进程pid 请教linux下c语言函数fork父进程打印子进程的PID

时间:2023-07-27 15:10:03

相关推荐

linux父进程中显示子进程pid 请教linux下c语言函数fork父进程打印子进程的PID

请教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);

}

我要举报

如以上问答内容为色情/暴力/低俗/不良/侵权等信息,可以点下面链接进行举报,我们会做出相应处理,感谢你的支持!

大家都在看

推荐资讯

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。