#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”传递给子进程?
调用 fork 后,您永远不知道哪个进程会先执行。您必须简单地断言您的代码可以正确处理进程间通信,无论现在发生什么。
您可以使用 pipe(2)或共享内存在同一主机上的不同进程之间传递数据。
#include <unistd.h>
int pipe(int pipefd[2]);
但是您也可以在调用 fork 之前将数据读入全局变量。 Fork 将在新进程中创建全局数据的副本。
使用 shmget
共享内存 example .
我是一名优秀的程序员,十分优秀!