3

So I want to pass a variable from one c program to another c program.

For example:

main()
{
char str[]="Hello,there!";
system("program2.exe");
}

And I want to use str[] in program2.exe. Is there a way to pass a variable to another program?

I used files to write data from first program and read data from second program but I want to know is there any other way to do this?

Is it good to use files for passing data from program to another?

  • Pass command line arguments,i.e, use `char command[strlen(str)+strlen("program2.exe")+2]; sprintf(command, "program2.exe %s",str); system(command);`. From the other program, use `int main(int argc,char** argv){ if(argc>1) printf("Got %s",argv[1]); }` – Spikatrix May 16 '15 at 10:14

2 Answers2

3

You can't literally pass a variable between two processes because each process on a system will generally have it's own memory space - each variable belongs to a process and therefore can't be accessed from another process (or so I believe). But you can pass data between processes using pipes.

Pipes are buffers that are implemented by the OS and are a much more effective method of sharing data between processes than files (yes, you can use files for inter-process communication). This is because files must be written to a disk before being accessed which makes them slow for inter-process communication. You'd also have to implement some kind of method for ensuring the two processes don't corrupt a file when reading and writing to it.

Also, pipes can be used to ensure continuous communication between two processes, making them useful in many situations. When using half duplex pipes (linked above), you can have a pipe for each process to establish a communication channel between them (i.e. a one way communication channel for each).

C Goldsworthy
  • 334
  • 2
  • 12
0

you can:
1) pass arguments to a program. 2) use sockets to communicate between processes.

Amir H
  • 482
  • 4
  • 10