#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<sys/stat.h>
#define SIZE 100
void main()
{
int shmid,status;
pid_t pid;
int i;
char *a,*b,d[100];
shmid=shmget(IPC_PRIVATE,SIZE,S_IRUSR | S_IWUSR);
pid=fork();
if(pid==0)
{
b=(char *) shmat(shmid,NULL,0);
printf("enter");
printf("%c",*b);
shmdt(b);
}
else
{
a=(char *) shmat(shmid,NULL,0);
printf("enter a string");
scanf("%s",&d);
strcpy(a,d);
shmdt(a);
}
}我试图将一个字符串从父进程传递给子进程。但是在将值扫描到"d“之前,程序切换到子进程。我应该如何纠正这个逻辑错误?我应该如何将这个字符串"d“传递给子进程呢?
发布于 2015-09-27 02:43:25
在调用fork之后,您永远不知道哪个进程将首先执行。无论现在发生什么,您必须简单地断言您的代码能够正确地处理进程间通信。
您可以使用pipe(2)或共享内存在同一主机上的不同进程之间传递数据。
#include <unistd.h>
int pipe(int pipefd[2]);但您也可以在调用fork之前将数据读取到全局变量中。Fork将在新进程中创建全局数据的副本。
使用shmget example共享内存。
发布于 2015-09-27 02:49:19
Fork是一个系统调用,它创建了两个进程,一个称为父进程,另一个称为子进程!要使它们能够通信,您需要应用您可以使用的进程间通信技术
1.Pipes
2.FIFO-also known as Named pipes
3.Shared Memory
4.Message Queue
5.Semaphore使用它们需要知道的一切都提到了here!示例代码写在描述后面
https://stackoverflow.com/questions/32800667
复制相似问题