上次我提问过。
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
int main(){
int arr[10]={0,};
pid_t pid;
int state;
pid = fork();
if(pid == -1) // error
{
printf("can't fork, error\n");
exit(-1);
}
else if (pid == 0) // Child ( producer )
{
printf("\nProducer is created.\n");
printf("array: ");
for(c=0; c<10; c++)
{
printf("%d ", arr[c]);
arr[c]=c+1;
}
}
else // Mother ( consumer )
{
pid=wait(&state);
sleep(1);
printf("\nConsumer takes control of array");
printf("\narray:");
for(j=0;j<10;j++)
{
printf(" %d", arr[j]);
}
printf("\nConsumer is done.");
printf("\narray: ");
for ( i =0; i<10; i++)
{
arr[i]=-1;
printf("%d ", arr[i]);
}
printf("\ndone\n");
exit(0);
}
return 0;}
我想要输出
0 0 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8 9 10
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
但是
我的输出是
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
我的代码有什么问题?
=
我写了这个问题, 很多人说我应该使用共享内存, 但我从来没有在类里面听过..
但我应该在 2 天内解决。
获得解决方案的简单方法是什么。
我找到了“shm*”,但是,没有比 shm* 更简单的方法来解决这个问题了吗?
如果存在,请教我一个简单的例子......
谢谢...
最佳答案
您可以交流 PIPE。这是另一种IPC机制。
来自Linux手册: int pipeline(int fd[2]) -- 创建一个管道并返回两个文件描述符 fd[0]、fd[1]。打开 fd[0] 进行读取,打开 fd[1] 进行写入。
您的要求的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t pid;
int arr[10]={0,};
int readbuffer[10];
int state, c, i, j;
pipe(fd);
if((pid = fork()) == -1)
{
printf("can't fork, error\n");
exit(-1);
}
else if(pid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "arr" through the output side of pipe */
printf("\nProducer is created.\n");
printf("array: ");
for(c=0; c<10; c++)
{
printf("%d ", arr[c]);
arr[c]=c+1;
}
write(fd[1], arr, (sizeof(int)*10));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
pid=wait(&state);
sleep(1);
printf("\nConsumer takes control of array");
/* Read in arr from the pipe */
nbytes = read(fd[0], arr, (sizeof(int)*10));
printf("\narray:");
for(j=0;j<10;j++)
{
printf(" %d", arr[j]);
}
printf("\nConsumer is done.");
printf("\narray: ");
for ( i =0; i<10; i++)
{
arr[i]=-1;
printf("%d ", arr[i]);
}
printf("\ndone\n");
exit(0);
}
return(0);
}
关于c - 当我调用 fork() 时如何共享内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43697803/