用Unix/Linux系统调用pipe、fork编写一个简单的程序
利用Unix/Linux系统调用pipe、fork等编写程序,运行时创建子进程,父进程通过管道向子进程发送一个数字M,子进程中启动程序,显示M行“Hello,world”...
利用Unix/Linux系统调用pipe、fork等编写程序,运行时创建子进程,父进程通过管道向子进程发送一个数字M,子进程中启动程序,显示M行“Hello,world”。
展开
1个回答
展开全部
参考我下面的程序, 可以通过修改宏定义 M 来修改发送的数字 M
#include <stdio.h>
#include <unistd.h>
#define M 6
int main()
{
int pipefd[2];
int pid;
int m;
if (pipe(pipefd) < 0)
{
printf("Unable to create pipe!\n");
return 1;
}
pid = fork();
if (pid > 0) //parent
{
m = M;
close(pipefd[0]); //close read end
write(pipefd[1], &m, sizeof(int)); //write M
wait(NULL); // wait for child complete
close(pipefd[1]);
}
else if (pid == 0)
{
close(pipefd[1]);
read(pipefd[0], &m, sizeof(int)); //read M
while(m>0)
{
printf("Hello world.\n");
m--;
}
close(pipefd[0]);
}
else
{
printf("Unable to fork!\n");
return 1;
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
#define M 6
int main()
{
int pipefd[2];
int pid;
int m;
if (pipe(pipefd) < 0)
{
printf("Unable to create pipe!\n");
return 1;
}
pid = fork();
if (pid > 0) //parent
{
m = M;
close(pipefd[0]); //close read end
write(pipefd[1], &m, sizeof(int)); //write M
wait(NULL); // wait for child complete
close(pipefd[1]);
}
else if (pid == 0)
{
close(pipefd[1]);
read(pipefd[0], &m, sizeof(int)); //read M
while(m>0)
{
printf("Hello world.\n");
m--;
}
close(pipefd[0]);
}
else
{
printf("Unable to fork!\n");
return 1;
}
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询