linux父进程中显示子进程pid,请教linux下c语言函数fork父进程打印子进程的PID
請教linux下c語言函數(shù)fork父進程打印子進程的PID
關(guān)注:296??答案:2??信息版本:手機版
解決時間 2019-01-14 04:55
雨不眠的下
2019-01-13 12:23
用于輸入:n (在父進程中輸入)
輸出:從1到n的整數(shù)(子進程負責打印)
父進程打印子進程的PID,然后等待子進程結(jié)束,最后輸出child complete,退出系統(tǒng)
最佳答案
逐風
2019-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樓時間的塵埃
2019-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);
}
我要舉報
如以上問答內(nèi)容為色情/暴力/低俗/不良/侵權(quán)等信息,可以點下面鏈接進行舉報,我們會做出相應處理,感謝你的支持!
大家都在看
推薦資訊
總結(jié)
以上是生活随笔為你收集整理的linux父进程中显示子进程pid,请教linux下c语言函数fork父进程打印子进程的PID的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux远程代码执行漏洞,Bash远程
- 下一篇: linux支持表情的字体,让应用程序支持