In this tutorial, we will discuss a simple way of passing data between two processes. In the following example, the function popen allows to invoke a new process. Here, a process od is created with option -c. The invoking program can send data to the invoked program as the invoked program is opened in write mode "w". Hence, the data can be sent to the invoked function by fwrite function as shown in the following example.
Source code to send the output of a process to another process
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
FILE *my_fp;
char buffer[BUFSIZ + 1];
sprintf(buffer, "This is a dummy text...\n");
my_fp = popen("od -c", "w");
if (my_fp != NULL) {
fwrite(buffer, sizeof(char), strlen(buffer), my_fp);
pclose(my_fp);
exit(EXIT_SUCCESS);
}
exit(EXIT_FAILURE);
}
Source code to send the output of a process to another process
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
FILE *file = popen("cat", "w");
int x = 0;
for(x=0;x<5;x++) {
fprintf(file, "My Count = %d\n", x);
}
pclose(file);
return 0;
}
Source code to send the output of a process to another process
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
FILE *read;
char buffer[50];
sprintf(buffer,"Linux System call Testing....");
read=popen("wc -c","w");
fwrite(buffer,sizeof(char),strlen(buffer),read);
pclose(read);
return 0;
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.