[Linux]多进程编程
创建两个子进程;一个子进程(生产者进程)依次向缓冲区写入整数0,1,2,...,9;另一个子进程(消费者进程)暂停5s后,从缓冲区读数,每次读一个,并将读出的数字从缓冲区...
创建两个子进程;一个子进程(生产者进程)依次向缓冲区写入整数0,1,2,...,9;另一个子进程(消费者进程)暂停5s后,从缓冲区读数,每次读一个,并将读出的数字从缓冲区删除,然后将数字显示出来;父进程等待子进程2(消费者进程)的退出信息,待收集到该信息后,父进程就返回。
展开
2个回答
展开全部
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
int i = 0;
int *nCount;
int pfd[2];
char szBuff[11] = {0};
int status;
pid_t pid;
pipe(pfd);
if (fork() == 0)
{
nCount = malloc(sizeof(int) * 10);
for (i = 0; i < 10; ++i)
{
nCount[i] = i;
sprintf(szBuff, "%s%d", szBuff, nCount[i]);
}
write(pfd[1], szBuff, strlen(szBuff));
free(nCount);
close(pfd[0]);
close(pfd[1]);
}
else
{
if (fork() == 0)
{
printf("sleep (5) !\n");
sleep(5);
read(pfd[0], szBuff, 10);
printf("%s\n", szBuff);
close(pfd[0]);
close(pfd[1]);
}
else
{
pid = wait(&status);
i = WEXITSTATUS(status);
printf("child is %d ,exit status =%d\n", pid, i);
pid = wait(&status);
i = WEXITSTATUS(status);
printf("child is %d ,exit status =%d\n", pid, i);
}
}
close(pfd[0]);
close(pfd[1]);
return 0;
}
-------------------------------------------------------
解释一下,由于fork出的进程有自己独立的空间,所以两个子进程通信用pipe(管道),由一个子进程malloc出空间,写给子进程2,子进程2接收后返回!
有不明白的,给我留言。。。。。
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
int i = 0;
int *nCount;
int pfd[2];
char szBuff[11] = {0};
int status;
pid_t pid;
pipe(pfd);
if (fork() == 0)
{
nCount = malloc(sizeof(int) * 10);
for (i = 0; i < 10; ++i)
{
nCount[i] = i;
sprintf(szBuff, "%s%d", szBuff, nCount[i]);
}
write(pfd[1], szBuff, strlen(szBuff));
free(nCount);
close(pfd[0]);
close(pfd[1]);
}
else
{
if (fork() == 0)
{
printf("sleep (5) !\n");
sleep(5);
read(pfd[0], szBuff, 10);
printf("%s\n", szBuff);
close(pfd[0]);
close(pfd[1]);
}
else
{
pid = wait(&status);
i = WEXITSTATUS(status);
printf("child is %d ,exit status =%d\n", pid, i);
pid = wait(&status);
i = WEXITSTATUS(status);
printf("child is %d ,exit status =%d\n", pid, i);
}
}
close(pfd[0]);
close(pfd[1]);
return 0;
}
-------------------------------------------------------
解释一下,由于fork出的进程有自己独立的空间,所以两个子进程通信用pipe(管道),由一个子进程malloc出空间,写给子进程2,子进程2接收后返回!
有不明白的,给我留言。。。。。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询