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);
    }
}

I was trying to pass a string from the parent process to the child process. But before scanning the value into "d" the program switches to the child process. How should I correct this logical error? And how should I pass this string "d" to the child process?

Adrian Krupa
  • 1,877
  • 1
  • 15
  • 24

2 Answers2

1

After call to fork was made you never know which process will execute first. You must simply assert your code handles properly interprocess communication, whatever happens now.

You can use pipe(2) or shared memory to pass data between different processes on same host.

#include <unistd.h>

int pipe(int pipefd[2]);

But you can also read data into global variable before call to fork. Fork will create a copy of global data in new process.


Shared memory using shmget example.

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
-1

Fork is a system call and it creates two processes one is called the parent and the other is called the child! To enable them to communicate you need to apply interprocess communication techniques You could use

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

Everything you need to know to use them is mentioned here!The sample codes are written after the description

Rahul Jha
  • 1,131
  • 1
  • 10
  • 25