2015-09-26 46 views
1
#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”传递给子进程?如何在父和子之间传递一个字符串?

+0

你为什么使用共享内存?管道是一个更好的选择。 –

+0

@FilipeGonçalves:作为学习共享内存的练习,或许?这显然是一个玩具程序。 –

回答

1

调用fork之后,您永远不会知道哪个进程将首先执行。无论现在发生什么,您都必须简单地声明代码处理正确的进程间通信。

您可以使用pipe(2)或共享内存在同一主机上的不同进程之间传递数据。

#include <unistd.h> 

int pipe(int pipefd[2]); 

但是您也可以在调用fork之前将数据读入全局变量。 Fork将在新流程中创建全球数据的副本。


使用共享内存shmgetexample

+0

我不想使用管道。我想使用共享内存。传递一个来自用户的字符串,并且子打印字符串。字符串应该存储在共享内存中。 –

+0

@rishabhagarwal附加shmget示例的链接 – 4pie0

-1

fork是一个系统调用,它创建两个进程,一个称为父进程,另一个称为子进程! 为使他们能沟通,你需要应用 你可以使用你需要知道使用它们

 1.Pipes 
    2.FIFO-also known as Named pipes 
    3.Shared Memory 
    4.Message Queue 
    5.Semaphore 

一切进程间通信技术中提到here!样本代码的说明之后写入

+0

Lol为什么downvote this –

相关问题