In this tutorial, we will investigate pipe call to understand inter-process communication. In pipe call, the child process is to be a different program from its parent, not a process running the same program.
Hence, we are developing two programs to understand how they work. Here, the first program, main_process.c, is data producer, and the second program, child_process.c, is data consumer.
Hence, we are developing two programs to understand how they work. Here, the first program, main_process.c, is data producer, and the second program, child_process.c, is data consumer.
Source code of main_process.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
int data_len;
int f_pipes[2];
const char data[] = "987";
char buffer[BUFSIZ + 1];
pid_t fork_status;
memset(buffer, '\0', sizeof(buffer));
if (pipe(f_pipes) == 0) {
fork_status = fork();
if (fork_status == (pid_t)-1) {
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
if (fork_status == 0) {
sprintf(buffer, "%d", f_pipes[0]);
(void)execl("child_process", "child_process", buffer, (char *)0);
exit(EXIT_FAILURE);
}
else {
data_len = write(f_pipes[1], data, strlen(data));
printf("%d - wrote %d bytes\n", getpid(), data_len);
}
}
exit(EXIT_SUCCESS);
}
Source code of child_process.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int data_len;
char buffer[BUFSIZ + 1];
int f_descriptor;
memset(buffer, '\0', sizeof(buffer));
sscanf(argv[1], "%d", &f_descriptor);
data_len = read(f_descriptor, buffer, BUFSIZ);
printf("%d - read %d bytes: %s\n", getpid(), data_len, buffer);
exit(EXIT_SUCCESS);
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.