请教linux下c语言函数fork父进程打印子进程的PID 20
用于输入:n(在父进程中输入)输出:从1到n的整数(子进程负责打印)父进程打印子进程的PID,然后等待子进程结束,最后输出childcomplete,退出系统...
用于输入:n (在父进程中输入)
输出:从1到n的整数(子进程负责打印)
父进程打印子进程的PID,然后等待子进程结束,最后输出child complete,退出系统 展开
输出:从1到n的整数(子进程负责打印)
父进程打印子进程的PID,然后等待子进程结束,最后输出child complete,退出系统 展开
1个回答
展开全部
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
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;
}
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询