What I know about PIPE is that it is used for a unidirectional communication and it helps to communicate between two related process. I have got the below PIPE programming code example from a book. I am trying to understand the code using printf and printing out all the points after every line of the code. But I am not understanding how the program is running after each and every line. My code is below:
PIPE:
//using PIPE to communicate with a child process
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
/* Write COUNT copies of MESSAGE to filename, pausing for a second
between each. */
void writer (const char* message, int count, FILE* filename)
{
for (; count > 0 ; -- count) {
printf("point 13\n");
/* Write the message to the filename, and send it off immediately.*/
fprintf (filename, "%s\n", message);
printf("point 14\n");
fflush (filename);
printf("point 15\n");
/* Snooze a while. */
sleep (1);
}
}
/* Read random strings from the filename as long as possible.
*/
void reader (FILE* filename)
{
char buffer[1024];
/* Read until we hit the end of the filename. fgets reads until
either a newline or the end-of-FILE. */
printf("point 16\n");
while (!feof (filename) && !ferror (filename) && fgets (buffer, sizeof (buffer), filename) != NULL)
fputs (buffer, stdout);
printf("point 17\n");
}
int main ()
{
int fds[2];
pid_t pid;
printf("point 1\n");
/* Create a pipe. FILE descriptors for the two ends of the pipe are
placed in fds. */
pipe (fds);
printf("point 2\n");
/* Fork a child process. */
pid = fork ();
printf("point 3\n");
if (pid == (pid_t) 0)
{
FILE* filename;
printf("point 4\n");
/* This is the child process. Close our copy of the write end of
the FILE descriptor. */
close (fds[1]);
printf("point 5\n");
/* Convert the read FILE descriptor to a FILE object, and read
from it. */
filename = fdopen (fds[0], "r");
printf("point 6\n");
reader (filename);
printf("point 7\n");
close (fds[0]);
printf("point 8\n");
}
else
{
/* This is the parent process. */
FILE* filename;
/* Close our copy of the read end of the FILE descriptor. */
close (fds[0]);
printf("point 9\n");
/* Convert the write FILE descriptor to a FILE object, and write
to it. */
filename = fdopen (fds[1], "w");
printf("point 10\n");
writer ("I want to learn c programming!", 5, filename);
printf("point 11\n");
close (fds[1]);
printf("point 12\n");
}
return 0;
}
I really need to understand the code. If I run my code then I am getting output like below in the Linux terminal but I am not sure why after the point 3,the point 9 is coming. Again after point 9 why point 3,4,5,10. Details explanation will help me.
point 1
point 2
point 3
point 9
point 3
point 4
point 5
point 10
point 13
point 14
point 15
point 6
point 16
I want to learn c programming!
point 13
point 14
point 15
I want to learn c programming!
point 13
point 14
point 15
I want to learn c programming!
point 13
point 14
point 15
I want to learn c programming!
point 13
point 14
point 15
I want to learn c programming!
point 11
point 12
point 17
point 7
point 8
pipe(int[]) function returns an array of size two integers. You need to understand the basic concepts here. A pipe can be used for unidirectional communication same as a water pipe. One thing you need to understand here is pipe is internally a file. So, as we use file descriptors for reading and writing content from/into a file similarly we need descriptors for reading/writing from/to a pipe. Now in your program when pipe(fds) is executed, a pipe is created and two descriptors are created for reading and writing into this pipe. These descriptors are fds[0](read end) and fds[1](write end).
Now, you need to understand about fork() here, this function created a new process(child process) by duplicating the existing process. Immediately after calling fork(), in child if is executed as fork returns 0 in child process and in parent the if condition fails as fork returns pid of child in parent process, hence else is executed. Rest you can observe your code.
Inside if you are closing fds[1], this will now enable your child process to only have read file descriptor for pipe and you are closing fds[0] in parent, this will enable your parent to have only write descriptor for pipe. Now, your child is able to only read from pipe and parent is only able to write from the pipe and you can observe the communication is from parent to child(parent is writing, child is reading). If you want a reverse communication than you need to create a new pipe. So, one pipe can be used for communication in one direction.
Now, you can understand rest of the program simply by understanding how a parent and child process will execute after fork. Now whichever process gets CPU time that process is executed, in this way you get an interleaved execution of child and parent process leaving you with the above output.
Related
Blow is an implementation of Sieve of Eratosthenes in C
#include "kernel/stat.h"
#include "kernel/types.h"
#include "user/user.h"
void cull(int p) {
int n;
while (read(0, &n, sizeof(n))) {
// n is not prime
if (n % p != 0) {
write(1, &n, sizeof(n));
}
}
}
void redirect(int k, int pd[]) {
close(k);
dup(pd[k]);
close(pd[0]);
close(pd[1]);
}
void right() {
int pd[2], p;
// read p
if (read(0, &p, sizeof(p))) {
printf("prime %d\n", p);
pipe(pd);
if (fork()) {
// parent
redirect(0, pd);
right();
} else {
redirect(1, pd);
cull(p);
}
}
}
int main(int argc, char *argv[]) {
int pd[2];
pipe(pd);
if (fork()) {
redirect(0, pd);
right();
} else {
redirect(1, pd);
for (int i = 2; i < 36; i++) {
write(1, &i, sizeof(i));
}
}
exit(0);
I am not quite following the logic here:
1). Why does redirect need to close pd1?
2). cull() is reading from the file descriptor 0, but in right() the child process will close 0. Why doesn't this cause any problem?
3). why it is necessary to use redirect here when we only want read from 0 and write to 1?
Update:
1). I found this implementation in the following blog post:
https://abcdlsj.github.io/post/mit-6.828-lab1xv6-and-unix-utilities/
2). I think the idea is borrowed from the inventor of this algorithm
3). I think the reason that the header is so is because it is implemented in a toy operating system for educational purpose.
The code is an adaptation of the paper Coroutine prime number sieve by M. Douglas McIlroy to the Xv6 operating system, a re-implementation of Version 6 Unix used for teaching. The technique is from 1968 as an experiment in co-routines via pipes. The paper explains the algorithm and rationale.
The program implements the sieve of Eratosthenes as a kind of production line, in which each worker culls multiples of one prime from a passing stream of integers, and new workers are recruited as primes are discovered.
When Unix came to be, my fascination with coroutines led me to badger its author, KenThompson, to allow writes in one process to go not only to devices but also to matching reads in another process.
...the coroutine sieve has been a standard demo for languages or systems that support interprocess communication. Implementations using Unix processes typically place the three coroutines—source, cull and sink—in distinct executable files.The fact that the whole program can be written as a single source file, in a language that supports neither concurrency nor IPC, is a tribute not only to Unix’s pipes, but also to its clean separation of program initiation into fork for duplicating address spaces and exec for initializing them.
I believe using stdin and stdout is an artifact of its origins in the early days of Unix when piping stdin and stdout between processes was first introduced. It makes a lot more sense in shell.
#!/bin/bash
source() {
seq 2 1000000
}
cull() {
while true
do
read n
(($n % $1 != 0)) && echo $n
done
}
sink() {
read p
echo $p
cull $p | sink &
}
source | sink
In C, as we'll see, it's simpler to skip the redirection and pass around pipes.
First, what's going on?
redirect is redirecting stdin and stdout to a pipe. 0 is stdin and 1 is stdout. This can be made more clear by using STDIN_FILENO and STDOUT_FILENO.
main makes a pipe.
main forks.
The child redirects stdout to the pipe.
The child streams numbers to the pipe via stdout.
The first number must be 2.
main redirects stdin to the pipe.
main calls right.
right reads the first prime, 2, from stdin which is a pipe to the number stream.
[number stream] ->(2) [right]
After the initial condition, a switcheroo happens inside right.
right makes a pipe.
right forks.
The child redirects its stdout to the pipe.
The child's stdin is still reading from the number stream.
The child calls cull.
cull reads from stdin (the number stream) and writes to stdout (right).
right redirects its stdin to the pipe, reading from cull.
right recurses.
[number stream] ->(n) [cull] ->(p) [right]
After the first call right is reading primes from cull and writing them to the real stdout. cull reads candidates from the number stream and writes primes to right.
When the number stream loop ends the process ends and closes its pipe to cull. Once all the numbers have been read from the pipe, cull to reads EOF ending its loop and its process, closing its pipe to right. right reads EOF and returns back to main which exits.
To explain redirect we need to understand redirection in C.
First, a simple one-way pipe.
int pd[2];
pipe(pd);
//parent
if (fork()) {
// Parent must close the input side else reading from pd[0] will
// continue to try to read from pd[1] even after the child closes
// their pipe.
close(pd[1]);
int p;
while( read(pd[0], &p, sizeof(p)) ) {
printf("p = %d\n", p);
}
fprintf(stderr, "parent done reading\n");
}
// child
else {
// Not strictly necessary, but the child will not be reading.
close(pd[0]);
for (int i = 2; i < 10; i++) {
write(pd[1], &i, sizeof(i));
}
// Tell the parent we're done writing to the pipe.
// The parent will get EOF on its next read. If the child
// does not close the pipe, the parent will hang waiting to read.
close(pd[1]);
fprintf(stderr, "child done writing\n");
// Pipes are closed automatically when a process exits, but
// let's simulate the child not immediately exiting to
// illustrate why it's important to explicitly close pipes.
sleep(1);
}
The parent and child share a pipe. The parent reads from one end, the child writes to the other. The child closes their write end when they're done so the parent doesn't hang trying to read. The parent closes their write end immediately so their pipe doesn't try to read from it.
Instead of passing the pipe around, redirect is redirecting the parent's half to stdin and the child's half to stdout. Let's do that in our simple example using dup2. dup2 duplicates a descriptor to another, first closing the target.
int pd[2];
pipe(pd);
if (fork()) {
// Redirect pd[0] to stdin.
dup2(pd[0], STDIN_FILENO);
// Parent still has to close its input side.
close(pd[1]);
int p;
while( read(STDIN_FILENO, &p, sizeof(p)) ) {
printf("p = %d\n", p);
}
fprintf(stderr, "parent done reading\n");
} else {
// Redirect pd[1] to stdout.
dup2(pd[1], STDOUT_FILENO);
// Close the original pd[1] so the parent doesn't try to read from it.
close(pd[1]);
for (int i = 2; i < 10; i++) {
write(STDOUT_FILENO, &i, sizeof(i));
}
// Tell the parent we're done writing.
close(STDOUT_FILENO);
fprintf(stderr, "child done writing\n");
sleep(1);
}
The final twist is dup. dup duplicates pd[k] to the lowest numbered descriptor currently not in use by the process. redirect(0, pd) closes descriptor 0 and then copies pd[0] to the lowest numbered descriptor: 0.
redirect(1, pd) closes descriptor 1 and then copies pd[1] to what it hopes is the lowest numbered descriptor: 1. If something else closed 0, redirect(1, pd) will copy pd[1] to descriptor 0 and the code will not work. This can be avoided by using dup2 which makes it explicit which file descriptor you're copying to.
// close(k) and dup(pd[k]) to k safely and explicitly.
dup2(pd[k], k);
redirect can be rewritten as:
void redirect(int k, int pd[]) {
dup2(pd[k], k);
close(pd[0]);
close(pd[1]);
}
Note that is all for a one-way pipe. cull uses bi-directional pipes, but the idea is the same.
By redirecting its pipe to stdin and stdout the program can use the pipe without having to pass the pipe around. This lets right read the first prime from the number generator and then let cull read the rest. It could also be done explicitly.
With some simpler examples in place, now we can answer the questions.
1). Why does redirect need to close pd[1]?
The parent must close the input side of its pipe, even after it's been duplicated or closed by the child, else the pipe will remain open and the parent will hang trying to read from it.
cull() is reading from the file descriptor 0, but in right() the child process will close 0. Why doesn't this cause any problem?
right closes its 0 and then copies pd[0] to 0. cull does not close 0, it closes pd[0]. cull reads from the original 0 which is the number generator.
Why it is necessary to use redirect here when we only want read from 0 and write to 1?
Because we need 0 and 1 to be different things at different times. We don't really want to read from 0 and write to 1. We want to read and write from pipes which happen to be attached to 0 and 1. The program is redirecting its pipes to 0 and 1 to demonstrate how Unix pipes and redirection works internally.
It took a dabbler like me some time to figure out how this program worked, it would have been a lot easier if I'd read the original paper and seen the shell script version first.
It can be rewritten to use explicit pipes. This avoids action at a distance, is easier to understand, and still demonstrates pipes and co-routines, but it no longer illustrates redirection.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void cull(int p, int read_d, int write_d) {
int n;
while (read(read_d, &n, sizeof(n))) {
if (n % p != 0) {
write(write_d, &n, sizeof(n));
}
}
}
void right(int read_d) {
int p;
if (read(read_d, &p, sizeof(p))) {
printf("prime %d\n", p);
int cull_pipe[2];
pipe(cull_pipe);
if (fork()) {
// right() reads from cull().
close(cull_pipe[1]);
right(cull_pipe[0]);
} else {
// cull() reads from the number generator and writes to right().
close(cull_pipe[0]);
cull(p, read_d, cull_pipe[1]);
close(cull_pipe[1]);
}
}
}
int main(int argc, char *argv[]) {
int pd[2];
pipe(pd);
if (fork()) {
// The first call to right() reads from the number generator.
close(pd[1]);
right(pd[0]);
} else {
close(pd[0]);
for (int i = 2; i < 6; i++) {
write(pd[1], &i, sizeof(i));
}
close(pd[1]);
}
exit(0);
}
Other notes:
The headers can be replaced with standard headers.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
I've been trying to implement shell-like functionality with pipes in an application and I'm following this example. I will reproduce the code here for future reference in case the original is removed:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
/**
* Executes the command "cat scores | grep Villanova | cut -b 1-10".
* This quick-and-dirty version does no error checking.
*
* #author Jim Glenn
* #version 0.1 10/4/2004
*/
int main(int argc, char **argv)
{
int status;
int i;
// arguments for commands; your parser would be responsible for
// setting up arrays like these
char *cat_args[] = {"cat", "scores", NULL};
char *grep_args[] = {"grep", "Villanova", NULL};
char *cut_args[] = {"cut", "-b", "1-10", NULL};
// make 2 pipes (cat to grep and grep to cut); each has 2 fds
int pipes[4];
pipe(pipes); // sets up 1st pipe
pipe(pipes + 2); // sets up 2nd pipe
// we now have 4 fds:
// pipes[0] = read end of cat->grep pipe (read by grep)
// pipes[1] = write end of cat->grep pipe (written by cat)
// pipes[2] = read end of grep->cut pipe (read by cut)
// pipes[3] = write end of grep->cut pipe (written by grep)
// Note that the code in each if is basically identical, so you
// could set up a loop to handle it. The differences are in the
// indicies into pipes used for the dup2 system call
// and that the 1st and last only deal with the end of one pipe.
// fork the first child (to execute cat)
if (fork() == 0)
{
// replace cat's stdout with write part of 1st pipe
dup2(pipes[1], 1);
// close all pipes (very important!); end we're using was safely copied
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
execvp(*cat_args, cat_args);
}
else
{
// fork second child (to execute grep)
if (fork() == 0)
{
// replace grep's stdin with read end of 1st pipe
dup2(pipes[0], 0);
// replace grep's stdout with write end of 2nd pipe
dup2(pipes[3], 1);
// close all ends of pipes
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
execvp(*grep_args, grep_args);
}
else
{
// fork third child (to execute cut)
if (fork() == 0)
{
// replace cut's stdin with input read of 2nd pipe
dup2(pipes[2], 0);
// close all ends of pipes
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
execvp(*cut_args, cut_args);
}
}
}
// only the parent gets here and waits for 3 children to finish
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
for (i = 0; i < 3; i++)
wait(&status);
}
I have trouble understanding why the pipes are being closed just before calling execvp and reading or writing any data. I believe it has something to do with passing EOF flags to processes so that they can stop reading writing however I don't see how that helps before any actual data is pushed to the pipe. I'd appreciate a clear explanation. Thanks.
I have trouble understanding why the pipes are being closed just before calling execvp and reading or writing any data.
The pipes are not being closed. Rather, some file descriptors associated with the pipe ends are being closed. Each child process is duping pipe-end file descriptors onto one or both of its standard streams, then closing all pipe-end file descriptors that it is not actually going to use, which is all of the ones stored in the pipes array. Each pipe itself remains open and usable as long as each end is open in at least one process, and each child process holds at least one end of one pipe open. Those are closed when the child processes terminate (or at least under the control of the child processes, post execvp()).
One reason to perform such closures is for tidiness and resource management. There is a limit on how many file descriptors a process may have open at once, so it is wise to avoiding leaving unneeded file descriptors open.
But also, functionally, a process reading from one of the pipes will not detect end of file until all open file descriptors associated with the write end of the pipe, in any process, are closed. That's what EOF on a pipe means, and it makes sense because as long as the write end is open anywhere, it is possible that more data will be written to it.
I want to learn how Linux pipes work! I wrote a small and easy program that use a pipe to communicate a string between parent and child process. However, the program results in a dead lock that I have not understood what is its cause.
Here is the code :
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define SIZE 100
int
main(int argc, char *argv[])
{
int pfd[2];
int read_pipe=0, write_pipe=0;
pid_t cpid;
char buf[SIZE];
/* PIPE ***************************************
* pipe() creates a pair of file descriptors, *
* pointing to a pipe inode, and places them *
* in the array pointed to by filedes. *
* filedes[0] is for reading, *
* filedes[1] is for writing *
**********************************************/
if (pipe(pfd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
read_pipe=pfd[0];
write_pipe=pfd[1];
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
char * hello = "I am a child process\n";
sleep(1);
// wait until there is some data in the pipe
while (read(read_pipe, buf, SIZE) > 0);
printf("Parent process has written : %s\n", buf);
write(write_pipe, hello, strlen(hello));
close(write_pipe);
close(read_pipe);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
char * hello = "I am a parent process\n";
write(write_pipe, hello, strlen(hello));
while (read(read_pipe, buf, SIZE) > 0);
printf("Child process has written : %s\n", buf);
close(write_pipe);
close(read_pipe);
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
In this link you'll find the proper mannipulation of PIPEs between parent and child. Your problem here is that the communication is not being correctly set-up.
The PIPE should be used to communicate in only one direction, so one process has to close the read descriptor and the other has to close the write descriptor. Otherwise what will happen is that the call to 'read'(both on the father and the son), since it can detect that there is another process with an open write descriptor on the PIPE, will block when it finds that the PIPE is empty (not return 0), until someone writes something in it. So, both your father and your son are getting blocked on their respective read.
There are two solutions to this:
.You create two PIPEs, one for the communication in each direction, and perform the initialization as explained in the link above. Here you have to remember to close the write descriptor when you are done sending the message, so the other process' read will return, or condition the loop to the count of bytes read (not to the return of read), so you won't perform another call when you read the whole message. For example:
int bread = 0;
while(bread < desired_count)
{
bread += read(read_pipe, buf + bread, SIZE - bread);
}
.You create one PIPE as you did, and modify the flags on the read descriptor, using fcntl to also have O_NONBLOCK, so the calls to read won't block when there's no information in the PIPE. Here you need to check on the return value of the read to know you received something, and go adding up until you get the full length of the message. Also you will have find a way to synchronize the two processes so they won't read messages that are not meant for them. I don't recommend you to use this option, but you can try it if you want using condition variables.
Maybe you can tell if you see any of yout printf() outputs?
Anyway, if you want to establish a two way communication between your paent and child, yout should use two pipes, one for writing data form parent to child an the other for writing from child to parent. Furthermore, your read loops may be dangerous: if the data comes in two or more chunks the second read() overwrites the first portion (I've never seen tha happen with local pipes, but for example with sockets). And of course, yout is not automatically null terminated after read(), so just printing int with "%s" may also cause problems.
I hope that gives you some ideas to try.
I have a problem with this exercise:
Write a program in C that creates a child and between father and child, there will be two-way communication using pipes. His father would read a file (whose name will be given the user) and will send letters to the child.
The child will count the number of words starting from with 'a'; if the number is, whether X of words, X, starting with 'a' is greater than 5, then the child will create his own child (grandchild). The grandchild of the establishment will send, by whatever means you deem possible, the grandfather * value of X number and exit. [By inference: if the number X is less than 6, then the child simply exits, and the 'would be grandparent' also exits.]
Note: Grandfather = initial process of the father, that father of his father's grandchild
Here is what I have done till now; please help me...
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd1[2], fd2[2], pid, status,sum=0, i;
char gram[100], x;
char buff[100];
char rev[1000];
FILE *fp;
if (pipe(fd1) == -1) { /* Create a pipe */
perror("pipe");
exit(1);
}
pid = fork();
switch (pid)
{
case -1:
perror ("Fork error\n");
exit(99); // in case of error
case 0:
close(fd1[1]);//Close the writing side
rev[1000]= read(fd1[0], buff, 1000); /* Read from the pipe */
/*for (i=0; i< 1000 ; i++)
{
rev[i] = read(fd1[0], buff, sizeof(buff));
}*/
while( rev[i] != '\0')
{
if (buff[i] == 'a' )
{ sum++;
i++;
}
if (rev[i] == "")
{
if (rev[i+1]) //elenxei to epomeno tou kenou
{
sum++;
i++;
}
}
i++;
}
printf("%d", sum);
exit(0);
default:
printf("dwse arxeio\n");
scanf("%s", gram);
close(fd1[0]);//Close the reading side
fp = fopen (gram,"r");
getc(fp);
fclose(fp);
write(fd1[1], buff, sizeof(buff)+1);
close(fd1[1]);//Close the writing side
wait(&status); // waits till the child process ends
}
}
You probably want to look at popen.
It starts a child process and returns a FILE * you can use to read/write to the childs stdin/stdout.
Let's call the three processes GP (for grandparent), PP (for parent process), and GC (for grandchild). In outline, I think what you need to do is:
GP creates two pipes (4 file descriptors) designated RP (read pipe) and WP (write pipe). That decribes how GP will use them; PP and GC will write on RP and read on WP.
GP forks, creating PP.
GP will close the write end of RP and the read end of WP.
GP will open the file.
GP will write whatever subset of the file is appropriate to PP via WP.
GP will close WP when there is no more data to transfer.
GP should also close the file it opened.
GP will then read from RP, probably stashing the data until it gets EOF.
If it gets any information back, GP will echo that information to standard output.
GP can then terminate.
Meanwhile, step 2 above created PP, who has to do some work:
PP needs to close the read end of RP and the write end of WP.
PP sits in a loop, reading data from WP, counting whatever is relevant.
When PP gets an EOF on WP, it can decide what it needs to do.
PP can now close the read end of WP.
If its counter X is bigger than 5, then (for reasons that only make sense in homework) it will fork to create GC; it can then exit.
If its counter X does not reach the threshold, then as far as the specification goes, it can terminate immediately. For debugging, you'll probably have it print something to stdout about what it did and why.
Now you have GP and GC around; remember that GC is an almost exact copy of PP, and (in particular) GC knows the value X just as well as PP did. So, GC does some work, too:
GC formats X as a string (probably - you could do binary data transfer if you prefer, but that passes the formatting buck to GP, that's all).
GC writes the formatted X on the write end of RP.
GC closes the write end of RP.
GC exits.
GC's step 3 ensures that GP wakes up from its step 8.
Judged as an industrial design, there is no point to creating GC; PP could perfectly well do what GC does. As a homework exercise, it passes muster. The key insight is in the comments above:
The crux of the matter is how to communicate from grandchild to grandfather. The good news is, the grandchild inherits the pipes open in the child.
The other key steps are closing the unused ends of the pipes and closing the pipes when there's nothing more to write. Without those closes, processes are apt to get stuck in deadlock. If GP fails to close the write end of RP, for example, it will never get EOF when reading from RP, because there is a process that could still write to RP - and that process is GP!
rev[1000]= read(fd1[0], buff, 1000); /* Read from the pipe */
What are you trying to accomplish with the lvalue here?
First, rev is declared as having 1000 elements, so rev[1000] is a buffer overrun...
Second, I suggest you look at the "Return value" section of the manual page for read(). It returns the number of bytes received (which may be smaller than the third parameter you specified), or 0 on end-of-file, or negative on failure. It will fill in the contents of buff with the actual data. I am not sure from your code what you are expecting the system call to act like but it doesn't seem to me like you are using it correctly.
You want to be doing something like this:
int r;
r = read(fd1[0], buff, sizeof(buff));
if (r < 0) { /* TODO: Handle error */ }
else if (r == 0) { /* TODO: Handle EOF */ }
else { /* TODO: Handle the fact that buff now contains 'r' bytes */ }
This question already has answers here:
Execute program from within a C program
(6 answers)
Closed 8 years ago.
How do I run another program from within my C program, I need to be able to write data into STDIN(while execution of program i have to provide input through stdin more than once) of the programed launched (and read line by line from it's STDOUT)
I need the solution to work under Linux.
while going through net i found below code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
void error(char *s);
char *data = "Some input data\n";
main()
{
int in[2], out[2], n, pid;
char buf[255];
/* In a pipe, xx[0] is for reading, xx[1] is for writing */
if (pipe(in) < 0) error("pipe in");
if (pipe(out) < 0) error("pipe out");
if ((pid=fork()) == 0) {
/* This is the child process */
/* Close stdin, stdout, stderr */
close(0);
close(1);
close(2);
/* make our pipes, our new stdin,stdout and stderr */
dup2(in[0],0);
dup2(out[1],1);
dup2(out[1],2);
/* Close the other ends of the pipes that the parent will use, because if
* we leave these open in the child, the child/parent will not get an EOF
* when the parent/child closes their end of the pipe.
*/
close(in[1]);
close(out[0]);
/* Over-write the child process with the hexdump binary */
execl("/usr/bin/hexdump", "hexdump", "-C", (char *)NULL);
error("Could not exec hexdump");
}
printf("Spawned 'hexdump -C' as a child process at pid %d\n", pid);
/* This is the parent process */
/* Close the pipe ends that the child uses to read from / write to so
* the when we close the others, an EOF will be transmitted properly.
*/
close(in[0]);
close(out[1]);
printf("<- %s", data);
/* Write some data to the childs input */
write(in[1], data, strlen(data));
/* Because of the small amount of data, the child may block unless we
* close it's input stream. This sends an EOF to the child on it's
* stdin.
*/
close(in[1]);
/* Read back any output */
n = read(out[0], buf, 250);
buf[n] = 0;
printf("-> %s",buf);
exit(0);
}
void error(char *s)
{
perror(s);
exit(1);
}
but this code is working fine if my C program(which needs to be executed usng exec) is reading input only once from stdin and returns output
once .but if my Cprogram(which needs to be executed usng exec) is taking input more than once(dont know exactly how many times it will read input from stdin)
and display output put mork than once(while execution display output line by line on stdout)
then this code is crashing. can any body suggest how to solve this problem?
Actually my C program(which needs to be executed usng exec) is displaying some output line by line and depending upon output i have to provide input on stdin
and number of this read/write is not constant.
Please help me resolve this issue.
You can use the select api to get notified when you can read/write a file descriptor.
So you would basically put your read and write calls into a loop, and run select to find out when the external program consumed some bytes or wrote something to stdout.