monitor bytes in stdin, stdout, and stderr in C - c

I need to count how many bytes are being sent to a child process through stdin, and how many bytes a child process is writing to stdout and stderr. The child process calls execvp, so I have no way to monitor those stats from within the process itself. My current tactic involves creating 3 additional child processes, one each to monitor each of the std streams through pipes (or in the case of stdin, just reading from stdin).
This tactic seems really frail at best, and I'm doing something strange which makes it so that the processes monitoring stdout/err cannot read from their respective ends of the pipes (and makes them hang indefinitely). Code below.
This creates the three helper child processes, and should allow them to count the stats:
void controles(struct fds *des)
{
int ex[2];
int err[2];
int n_in = 0;
int c_in;
int n_ex = 0;
int c_ex;
int n_err = 0;
int c_err;
pipe(ex);
pipe(err);
/*has two fields, for the write end of the stdout pipe and the stderr pipe. */
des->err = err[1];
des->ex = ex[1];
switch (fork()) {
case 0: /*stdin */
while (read(0, &c_in, 1) == 1)
n_in++;
if (n_in > 0)
printf("%d bytes to stdin\n", n_in);
exit(n_in);
default:
break;
}
switch (fork()) {
case 0: /*stdout */
close(ex[1]);
/*pretty sure this is wrong */
while (read(ex[0], &c_ex, 1) == 1) {
n_ex++;
write(1, &c_ex, 1);
}
if (n_ex > 0)
printf("%d bytes to stdout\n", n_ex);
close(ex[0]);
exit(n_ex);
default:
close(ex[0]);
}
switch (fork()) {
case 0: /*error */
close(err[1]);
/*also probably have a problem here */
while (read(err[0], &c_err, 1) == 1) {
n_err++;
write(2, &c_err, 1);
}
if (n_err > 0)
printf("%d bytes to stderr\n", n_err);
close(err[0]);
exit(n_err);
default:
close(err[0]);
}
}
and this is a code fragment (within the child process) which sets up the two fd's from the fds struct so that the child process should write to the pipe instead of stdin/stderr.
dup2(des.ex, 1);
dup2(des.err, 2);
close(des.ex); close(des.err); /*Is this right?*/
execvp(opts->exec, opts->options); /*sure this is working fine*/
I'm lost, any help would be appreciated.

I think your code could be improved by breaking things apart a little; the accounting and copying routines are all basically the same task, and if you choose to continue down the road with multiple processes, can be written simply:
void handle_fd_pair(char *name, int in, int out) {
char buf[1024];
int count = 0, n;
char fn[PATH_MAX];
snprintf(fn, PATH_MAX - 1, "/tmp/%s_count", name);
fn[PATH_MAX-1] = '\0';
FILE *output = fopen(fn, "w");
/* handle error */
while((n = read(in, buf, 1024)) > 0) {
count+=n;
writen(out, buf, n); /* see below */
}
fprintf(output, "%s copied %d bytes\n", name, count);
fclose(output);
}
Rather than one-char-at-a-time, which is inefficient for moderate amounts of data, we can handle partial writes with the writen() function from the Advanced Programming in the Unix Environment source code:
ssize_t /* Write "n" bytes to a descriptor */
writen(int fd, const void *ptr, size_t n)
{
size_t nleft;
ssize_t nwritten;
nleft = n;
while (nleft > 0) {
if ((nwritten = write(fd, ptr, nleft)) < 0) {
if (nleft == n)
return(-1); /* error, return -1 */
else
break; /* error, return amount written so far */
} else if (nwritten == 0) {
break;
}
nleft -= nwritten;
ptr += nwritten;
}
return(n - nleft); /* return >= 0 */
}
With the helper in place, I think the rest can go more easily. Fork a
new child for each stream, and give the in[0] read-end, out[1] and
err[1] write-ends of the pipes to the child.
All those close() calls in each child are pretty ugly, but trying to
write a little wrapper around an array of all the fds, and exempting the
ones passed in as arguments, also seems like trouble.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#ifndef PATH_MAX
#define PATH_MAX 128
#endif
void handle_fd_pair(char *name, int in, int out) {
char buf[1024];
int count = 0, n;
char fn[PATH_MAX];
snprintf(fn, PATH_MAX - 1, "/tmp/%s_count", name);
fn[PATH_MAX-1] = '\0';
FILE *output = fopen(fn, "w");
/* handle error */
while((n = read(in, buf, 1024)) > 0) {
count+=n;
writen(out, buf, n); /* see below */
}
fprintf(output, "%s copied %d bytes\n", name, count);
fclose(output);
}
int main(int argc, char* argv[]) {
int in[2], out[2], err[2];
pid_t c1, c2, c3;
pipe(in);
pipe(out);
pipe(err);
if ((c1 = fork()) < 0) {
perror("can't fork first child");
exit(1);
} else if (c1 == 0) {
close(in[0]);
close(out[0]);
close(out[1]);
close(err[0]);
close(err[1]);
handle_fd_pair("stdin", 0, in[1]);
exit(0);
}
if ((c2 = fork()) < 0) {
perror("can't fork second child");
exit(1);
} else if (c2 == 0) {
close(in[0]);
close(in[1]);
close(out[1]);
close(err[0]);
close(err[1]);
handle_fd_pair("stdout", out[0], 1);
exit(0);
}
if ((c3 = fork()) < 0) {
perror("can't fork third child");
exit(1);
} else if (c3 == 0) {
close(in[0]);
close(in[1]);
close(out[0]);
close(out[1]);
close(err[1]);
handle_fd_pair("stderr", err[0], 2);
exit(0);
}
/* parent falls through to here, no children */
close(in[1]);
close(out[0]);
close(err[0]);
close(0);
close(1);
close(2);
dup2(in[0], 0);
dup2(out[1], 1);
dup2(err[1], 2);
system(argv[1]);
exit(1); /* can't reach */
}
It seems to work for toy applications anyway :)
$ ./dup cat
hello
hello
$ ls -l *count
-rw-r--r-- 1 sarnold sarnold 22 2011-05-26 17:41 stderr_count
-rw-r--r-- 1 sarnold sarnold 21 2011-05-26 17:41 stdin_count
-rw-r--r-- 1 sarnold sarnold 22 2011-05-26 17:41 stdout_count
$ cat *count
stderr copied 0 bytes
stdin copied 6 bytes
stdout copied 6 bytes
I think it is worth pointing out that you could also implement this
program with only one process, and use select(2) to determine which
file descriptors need reading and writing.

Overall, I think you're on the right track.
One problem is that in your stderr and stdout handlers, which should be picking bytes off the pipe and writing to the real stderr/stdout, you're writing back to the same pipe.
It would also be helpful to see how you start the child processes. You gave a code fragment to close the real stderr and then dup2 the pipe fd back to stderr's fd, but you probably want this in the parent process (after fork and before exec) so that you don't need to modify the source code to the child process. You should be able to do this generically all from the parent.

Related

Broken phone app in c with pipes and fork [duplicate]

So I have a project to do but I am completely stumped. I have spent ten hours and have gotten nowhere. I don't specifically want the code to the answer, but some pseudocode and good hints in the right direction would help a heap!!
It forks a number of processes, k - a command-line argument, connected by pipes - each process is connected to the next, and the last process is connected to the first. Process number k sends its message on to process number (k+1)%n.
Process 0 reads a line from stdin. It then transmits it to process 1. Each other process reads the line, increments the first byte of the string by 1, and then relays the line to the next process. As it relays, it prints a status message (shown below).
When the message gets back to process 0, it is output to the standard output as well. When a process receives EOF (either from pipe, if its a process other than 0, or from stdin, for process 0), it prints the final string. This will close all pipes.
The expected output is:
$ ./ring 4
hello
process #0 (32768) sending message: hello
process #1 (32769) relaying message: iello
process #2 (32770) relaying message: jello
process #3 (32767) relaying message: kello
I hear kello
^C
$
What I have written so far:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 80
#define READ_END 0
#define WRITE_END 1
int main(int argc, char *argv[])
{
char readmsg[BUFFER_SIZE], readmsg2[BUFFER_SIZE], final[BUFFER_SIZE];
int pid, process;
int parent_child[2], child_parent[2];
process = 0;
if (pipe(child_parent) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
if (pipe(parent_child) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid > 0) {
/* PARENT */
read(0, &readmsg, BUFFER_SIZE);
printf("process #%d (%d) sending message: %s",
0, getpid(), readmsg);
write(parent_child[WRITE_END], &readmsg, BUFFER_SIZE);
close(parent_child[WRITE_END]);
} else {
/* CHILD */
read(parent_child[READ_END], &readmsg2, BUFFER_SIZE);
readmsg2[0] += 1;
printf("process #%d (%d) relaying message: %s",
1, getpid(), readmsg2);
process += 1;
write(child_parent[WRITE_END], &readmsg2, BUFFER_SIZE);
}
read(child_parent[READ_END], &final, BUFFER_SIZE);
printf("I hear %d %s", pid - getpid(), final);
return 0;
}
What it does currently is read in a string from stdin, pass it to the first process and print process 0 (can't actually get the 0 though, simply printing 0), it then pipes the string to process 1 which distorts byte 1 and then writes to a pipe again and then outside of the pipes, the string is read and outputs the distorted string.
$ ./ring
hello
process #0 (6677) sending message: hello
process #1 (6678) relaying message: iello
I hear -6678 iello
^C
$
I don't know where to go from here. Thank you in advance, anything will help!!
Given some help this is what I have now:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 80
#define READ_END 0
#define WRITE_END 1
int main(int argc, char **argv) {
char buf[BUFFER_SIZE];
int process, rings, pid, pid_n, pid_n1, pid_1, i;
int Pn[2]; //Pipe for process n -> 0
int Pn_1[2]; //Pipe for process n-1 -> n
int Pn_2[2]; //Pipe for process n-2 -> n-1
int P_0[2]; //Pipe for process 0 -> 1
process = 0;
if (argc == 2) {
rings = atoi(argv[1]);
} else {
fprintf(stderr, "Usage: %s n, where n is number of rings\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((pid = fork()) < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid == 0) {
if ((pid_n = fork()) < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid_n == 0) {
/* CHILD */
close(Pn[WRITE_END]);
close(Pn_1[READ_END]);
} else {
/* PARENT */
close(Pn[READ_END]);
close(Pn_1[WRITE_END]);
}
for (i = 0; i < rings; i++) {
if ((pid_n1 = fork()) < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid_n1 == 0) {
/* CHILD */
close(Pn_1[WRITE_END]);
close(Pn_2[READ_END]);
} else {
/* PARENT */
close(Pn_1[READ_END]);
close(Pn_2[WRITE_END]);
}
}
/* Not sure about these last ones */
if ((pid_1 = fork()) < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid_1 == 0) {
/* CHILD */
close(P_n2[WRITE_END]);
close(P_0[READ_END]);
} else {
/* PARENT */
close(P_n2[READ_END]);
close(P_0[WRITE_END]);
}
} else {
/* PARENT */
read(0, &buf, BUFFER_SIZE);
buf[BUFFER_SIZE - 1] = '\0';
printf("process first # (%d) sending message: %s", getpid(), buf);
write(P_0[WRITE_END], &buf, BUFFER_SIZE);
read(Pn[READ_END], &buf, BUFFER_SIZE);
buf[BUFFER_SIZE - 1] = '\0';
printf("I hear %s", buf);
}
return 0;
}
This is a diagram I drew for myself showing how the processes are to be interconnected:
p4
C5 <--------- C4
/ \
p5 / p3 \
/ \
o----> C0 ---->o C3
\ /
p0 \ p2 /
\ /
C1 ---------> C2
p1
The Cn represent the processes; C0 is the parent process. The pn represent the pipes; the other two lines are standard input and standard output. Each child has a simple task, as befits children. The parent has a more complex task, mainly ensuring that exactly the right number of file descriptors are closed. In fact, the close() is so important that I created a debugging function, fd_close(), to conditionally report on file descriptors being closed. I used that too when I had silly mistakes in the code.
The err_*() functions are simplified versions of code I use in most of my programs. They make error reporting less onerous by converting most error reports into a one-line statement, rather than requiring multiple lines. (These functions are normally in 'stderr.c' and 'stderr.h', but those files are 750 lines of code and comment and are more comprehensive. The production code has an option to support prefixing each message with a PID, which is also important with multi-process systems like this.)
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
enum { BUFFER_SIZE = 1024 };
typedef int Pipe[2];
static int debug = 0;
static void fd_close(int fd);
/* These functions normally declared in stderr.h */
static void err_setarg0(const char *argv0);
static void err_sysexit(char const *fmt, ...);
static void err_usage(char const *usestr);
static void err_remark(char const *fmt, ...);
static void be_childish(Pipe in, Pipe out)
{
/* Close irrelevant ends of relevant pipes */
fd_close(in[1]);
fd_close(out[0]);
char buffer[BUFFER_SIZE];
ssize_t nbytes;
while ((nbytes = read(in[0], buffer, sizeof(buffer))) > 0)
{
buffer[0]++;
if (write(out[1], buffer, nbytes) != nbytes)
err_sysexit("%d: failed to write to pipe", (int)getpid());
}
fd_close(in[0]);
fd_close(out[1]);
exit(0);
}
int main(int argc, char **argv)
{
err_setarg0(argv[0]);
int nkids;
if (argc != 2 || (nkids = atoi(argv[1])) <= 1 || nkids >= 10)
err_usage("n # for n in 2..9");
err_remark("Parent has PID %d\n", (int)getpid());
Pipe pipelist[nkids];
if (pipe(pipelist[0]) != 0)
err_sysexit("Failed to create pipe #%d", 0);
if (debug)
err_remark("p[0][0] = %d; p[0][1] = %d\n", pipelist[0][0], pipelist[0][1]);
for (int i = 1; i < nkids; i++)
{
pid_t pid;
if (pipe(pipelist[i]) != 0)
err_sysexit("Failed to create pipe #%d", i);
if (debug)
err_remark("p[%d][0] = %d; p[%d][1] = %d\n", i, pipelist[i][0], i, pipelist[i][1]);
if ((pid = fork()) < 0)
err_sysexit("Failed to create child #%d", i);
if (pid == 0)
{
/* Close irrelevant pipes */
for (int j = 0; j < i-1; j++)
{
fd_close(pipelist[j][0]);
fd_close(pipelist[j][1]);
}
be_childish(pipelist[i-1], pipelist[i]);
/* NOTREACHED */
}
err_remark("Child %d has PID %d\n", i, (int)pid);
}
/* Close irrelevant pipes */
for (int j = 1; j < nkids-1; j++)
{
fd_close(pipelist[j][0]);
fd_close(pipelist[j][1]);
}
/* Close irrelevant ends of relevant pipes */
fd_close(pipelist[0][0]);
fd_close(pipelist[nkids-1][1]);
int w_fd = pipelist[0][1];
int r_fd = pipelist[nkids-1][0];
/* Main loop */
char buffer[BUFFER_SIZE];
while (printf("Input: ") > 0 && fgets(buffer, sizeof(buffer), stdin) != 0)
{
int len = strlen(buffer);
if (write(w_fd, buffer, len) != len)
err_sysexit("Failed to write to children");
if (read(r_fd, buffer, len) != len)
err_sysexit("Failed to read from children");
printf("Output: %.*s", len, buffer);
}
fd_close(w_fd);
fd_close(r_fd);
putchar('\n');
int status;
int corpse;
while ((corpse = wait(&status)) > 0)
err_remark("%d exited with status 0x%.4X\n", corpse, status);
return 0;
}
static void fd_close(int fd)
{
if (debug)
err_remark("%d: close(%d)\n", (int)getpid(), fd);
if (close(fd) != 0)
err_sysexit("%d: Failed to close %d\n", (int)getpid(), fd);
}
/* Normally in stderr.c */
static const char *arg0 = "<undefined>";
static void err_setarg0(const char *argv0)
{
arg0 = argv0;
}
static void err_usage(char const *usestr)
{
fprintf(stderr, "Usage: %s %s\n", arg0, usestr);
exit(1);
}
static void err_vsyswarn(char const *fmt, va_list args)
{
int errnum = errno;
fprintf(stderr, "%s:%d: ", arg0, (int)getpid());
vfprintf(stderr, fmt, args);
if (errnum != 0)
fprintf(stderr, " (%d: %s)", errnum, strerror(errnum));
putc('\n', stderr);
}
static void err_sysexit(char const *fmt, ...)
{
va_list args;
va_start(args, fmt);
err_vsyswarn(fmt, args);
va_end(args);
exit(1);
}
static void err_remark(char const *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
Example output:
$ ./pipecircle 9
Parent has PID 34473
Child 1 has PID 34474
Child 2 has PID 34475
Child 3 has PID 34476
Child 4 has PID 34477
Child 5 has PID 34478
Child 6 has PID 34479
Child 7 has PID 34480
Child 8 has PID 34481
Input: Hello
Output: Pello
Input: Bye
Output: Jye
Input: ^D
34474 exited with status 0x0000
34477 exited with status 0x0000
34479 exited with status 0x0000
34476 exited with status 0x0000
34475 exited with status 0x0000
34478 exited with status 0x0000
34480 exited with status 0x0000
34481 exited with status 0x0000
$
It seems to me that you are pretty close, as this works for two processes. What you need to do now is loop to create more processes from the parent.
(k=N+1 processes: proc0 = parent, proc1, ..., procN)
Create a pipe Pn, that will be for procN->proc0
Create a pipe Pn-1, that will be for procN-1->procN
Create relaying fork procN
fork closes Pn output and Pn-1 input
parent closes Pn input and Pn-1 output
(loop here)
Create a pipe Pi-2, that will be for procI-2->procI-1
Create relaying fork procI-1
fork closes Pi-1 output and Pi-2 input
parent closes Pi-1 input and Pi-2 output
...
Create a pipe P0 that will be for proc0->proc1
Create relaying fork proc1
fork closes P1 output and P0 input
parent closes P1 input and P0 output
(end loop)
(parent final code:)
Read from stdin
Write on P0
Read on Pn
Write on stdout
Once created with fork(), the child processes (i.e. apart from proc0) close the input of the pipe (the output of the other is already closed!), read the message on one, write on the other and exit.
Some remarks on your current code:
The child shouldn't execute that list bit, when you read on child_parent.
You don't need that many buffers (you only need one, that will turn into one per process after the fork).
Put some terminating null bytes before printing :)
It's good practice to close the ends that you're not going to need

How to synchronize read and write in the pipe in C?

Complete C beginner here.
I am trying to write some strings from the child process and read the strings in the parent process. But it looks like I haven't implemented the read and write properly. So my parent just reads the first string it gets. Below is my code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <stdbool.h>
#include <ctype.h>
/* Function declaration */
bool isNumeric(char* str);
int main(int argc, char* argv[]) {
// Check if input is recieved
if (argc == 1) {
printf("Input not received!\n");
exit(1);
}
// Check if the input is an int
if (isNumeric(argv[1]) == 0) {
printf("Input is not an Integer!\n");
exit(1);
}
// Initialize pipe
int fd[2];
pid_t childpid;
pipe(fd);
childpid = fork();
if (childpid == -1) {
printf("fork failed");
exit(1);
}
else if (childpid > 0) {
char string[100];
close(fd[1]);
printf("PARENT START\n");
while (read(fd[0], string, sizeof(string)) > 0) {
printf("%s\n", string);
}
printf("PARENT END\n");
close(fd[0]);
}
else {
close(fd[0]);
char string[100];
string[0] = '\0';
printf("CHILD START\n");
for (int i = 0; i < 5; i++) {
sprintf(string, "%d", i);
write(fd[1], string, strlen(string)+1);
}
printf("CHILD END\n");
close(fd[1]);
exit(0);
}
}
The output is just
PARENT START
CHILD START
CHILD END
0
PARENT END
My expected output is
PARENT START
CHILD START
CHILD END
0
1
2
3
4
PARENT END
I spent hours trying to synchronize the process, but I couldn't figure out how to fix the problem.
You ignore the return value of read, so the call to printf stops at the first zero byte. You send the messages delimited by zero bytes. Where's the code to find the zero bytes in the received data and extract the messages from the pipe?
You have code to send a message. It separates the messages with a terminating zero byte. Where's the code to receive a message, searching the incoming stream of data for zero bytes and passing on the data prior to it as a message?
Here's some ugly, inefficient code to receive a message. It checks the incoming stream of bytes for the terminating zero byte. It returns 0 on end of file, negative on error and 1 on success.:
int recvMessage (int fd, char* buf, int len)
{
while (len > 0)
{
int r = read(fd, buf, 1);
if (r <= 0) // pipe closed or error
return r;
if (*buf == 0) // we received a terminating zero byte
return 1;
buf++;
len--;
}
return -2; // message larger than buffer
}
Five things you need to learn:
sizeof(string) doesn't return the length of a string, much less one you haven't read in yet! It always returns 100 in this case.
write is not guaranteed to write the number of bytes provided as its third argument. You need to call write repeatedly until the entire buffer you want to write has been written.
read is not guaranteed to read the number of bytes provided as its third argument. You need to call read repeatedly until you've read the desired number of bytes.
In this case, you don't want to read a specific number of bytes. You want to read until one of the character you've read is a NUL.
Unless you pass 1 for read's third parameter, you might end up reading too much. This is not a problem; you just need to factor that in the next time you read.
Writer
Replace
write(fd[1], string, strlen(string)+1);
with
char *p = string;
size_t n = strlen(string) + 1;
while (n > 0) {
ssize_t rv = write(fd[1], p, n);
if (rv == -1) {
perror("write");
exit(1);
}
n -= rv;
p += rv;
}
Reader
Replace
char string[100];
while (read(fd[0], string, sizeof(string)) > 0) {
...
}
with
#define BLOCK_SIZE 100
char *string = NULL;
size_t size = 0;
size_t len = 0;
while (1) {
// Increase the buffer size if necessary.
if (size < len + BLOCK_SIZE) {
char *tmp = realloc(string, len + BLOCK_SIZE);
if (!tmp) {
perror("realloc");
exit(1);
}
string = tmp;
}
// Read from the pipe.
ssize_t rv = read(fd[0], string+len, BLOCK_SIZE);
if (rv == -1) {
perror("read");
exit(1);
}
// Handle EOF
if (rv == 0)
break;
len += rv;
// Check if we've received a message (or even more than one).
while (1) {
for (size_t i=0; i<len; ++i) {
if (!string[i]) {
// Handle a message.
...
len -= i+1;
memmove(string, string+i+1, len);
break;
}
}
}
}
// Handle a partial message.
if (len) {
fprintf(stderr, "Premature EOF");
exit(1);
}
free(string);

Why does program hang on child to parent communication?

I am trying to understand why my program hangs. The Parent sends input froma
file it reads to the child program, and the child program will send the result of its computation back to it's parent. However, I have trouble sending the message back through a second pipe. The parent seems to hang when reading from the pipe.
From the other posts, I have read it seems to indicate that the parent should wait for the child to finish by using wait or waitpid (which in my case both of them does not resolve my issue).
I have notice by adding print statement that neither the PARENT or the CHILD finishes.. Could someone please explain to me why this is happening?
Why does this not work?
int main(int argc,char** argv) {
char buffer[1];
int i;
int fd1[2]; int fd2[2];
pipe(fd1); pipe(fd2);
pid_t pid;
// FIRST PROCESS.
// -------------------
pid = fork();
if(pid == 0) {
int cnt;
dup2(fd1[0], STDIN_FILENO);
dup2(fd2[1], STDOUT_FILENO);
for (i = 0; i < 2; i++) {
close(fd1[i]);
close(fd2[i]);
}
while(read(STDIN_FILENO, buffer, sizeof(buffer)) > 0) {
fprintf(stderr, "( %s )", buffer);
cnt = cnt + *buffer - 48;
}
write(STDOUT_FILENO, &cnt, sizeof(cnt));
exit(0);
}
// PARENT.
// ------------------------
int file = open(argv[1], O_RDONLY);
// READ THE FILE.
while(read(file, buffer, 1) > 0) {
if (48 <= *buffer && *buffer <= 57) {
// PIPE TO CHILD.
write(fd1[1], buffer, 1);
}
}
// WAIT FOR CHILD TO FINISH SENDING BACK.
// int status = 0;
// waitpid(pid, &status, 0);
// THIS BLOCK DOESN'T RESOLVE ANYTHING. IT HANGS AT WAIT OR WAITPID.
// **** THIS IS THE PART WHERE IT DOESN'T WORK.
while(read(fd2[0], buffer, 1) > 0) {
fprintf(stderr, "RESULT : %s", buffer);
}
// CLOSING PIPES
for (i = 0; i < 2; i++) {
close(fd1[i]);
close(fd2[i]);
}
close(file);
exit(0);
}
You aren't closing enough file descriptors in the parent soon enough.
Rule of thumb: If you
dup2()
one end of a pipe to standard input or standard output, close both of the
original file descriptors returned by
pipe()
as soon as possible.
In particular, you should close them before using any of the
exec*()
family of functions.
The rule also applies if you duplicate the descriptors with either
dup()
or
fcntl()
with F_DUPFD
Now, your child process is following the RoT perfectly. But the corollary for parent processes is that they need to close the unused ends of the pipe, and they must close the write end of a pipe that they use to signal EOF to the reading end of that pipe. This is where your code fails.
Arguably, before reading the file, the parent process should close the read end of the pipe it uses to write to the child, and it should close the write end of the pipe it uses to read from the child.
Then, after reading the whole of the file, it should close the write end of the pipe to the child, before going into the 'read from child' loop. That loop never terminates because the parent still has the write end of the pipe open, so there's a process that could (but won't) write to the pipe.
Also, since the child writes the bytes of an integer onto a pipe, the parent should read the bytes of an integer. Using char buffer[1]; with a %s format is pointless; you need a null terminator for the string, and a single char buffer can't hold both a null byte and any data.
Along with various other improvements ('0' instead of 48, for example), you might end up with:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
int fd1[2];
int fd2[2];
char buffer[1];
pipe(fd1);
pipe(fd2);
pid_t pid = fork();
if (pid == 0) {
int cnt = 0;
dup2(fd1[0], STDIN_FILENO);
dup2(fd2[1], STDOUT_FILENO);
for (int i = 0; i < 2; i++) {
close(fd1[i]);
close(fd2[i]);
}
while (read(STDIN_FILENO, buffer, sizeof(buffer)) > 0) {
fprintf(stderr, "(%c)", buffer[0]); // Changed
cnt = cnt + buffer[0] - '0';
}
putc('\n', stderr); // Aesthetics
write(STDOUT_FILENO, &cnt, sizeof(cnt));
exit(0);
}
int file = open(argv[1], O_RDONLY);
if (file < 0) {
fprintf(stderr, "failed to open file '%s' for reading\n", argv[1]);
exit(EXIT_FAILURE);
}
close(fd1[0]); // Added
close(fd2[1]); // Added
while (read(file, buffer, sizeof(buffer)) > 0) {
if ('0' <= buffer[0] && buffer[0] <= '9') {
write(fd1[1], buffer, sizeof(buffer));
}
}
close(file); // Moved
close(fd1[1]); // Added
// Rewritten
int result;
while (read(fd2[0], &result, sizeof(result)) == sizeof(result)) {
fprintf(stderr, "RESULT : %d\n", result);
}
close(fd2[0]); // Added
// Close loop removed
return 0;
}
If that is stored in file pipe71.c and compiled, I get the following outputs when it is run:
$ ./pipe71 pipe71.c
(2)(0)(1)(2)(2)(2)(1)(1)(2)(0)(0)(2)(1)(0)(2)(2)(1)(0)(2)(1)(2)(0)(0)(0)(0)(0)(1)(0)(1)(1)(0)(2)(1)(0)(0)(0)(0)(9)(1)(1)(1)(1)(2)(0)(2)(0)(0)
RESULT : 49
$ ./pipe71 pipe71
(0)(0)(8)(0)(0)(2)(2)(0)(8)(1)(1)(5)(1)(1)(1)(1)(5)(1)(1)(1)(8)(5)(1)(9)(8)(5)(1)(1)(0)(4)(4)(4)(6)(0)(2)(8)(0)(0)(0)(2)(7)(1)(3)(8)(3)(0)(4)(3)(0)(4)(9)(0)(0)(0)(0)(7)(1)(9)(8)(1)(3)(0)
RESULT : 178
$

C Using pipes to transfer data to write to file using shared memory

I am trying to use pipes in C. I have two create two pipes between parent and child process.I have to read a file in chunks of 4096 bytes (or smaller if there is less) and I have to send through the pipes the amount of data that was read and how many times there have been readings. For example, to copy a 6KB
file, the parent writes the first 4KB data of the file to the shared memory and send two integers, 1 and 4096, to the child via the pipe. The child receives these two numbers, copies 4096 bytes from the shared memory to the output file, and sends back 1 to the parent via the other pipe. After receiving 1,
the parent copies the left 2KB data to the shared memory and send 2 and 2048 to the child. The child receives them from the pipe, copies 2048 bytes to the output file, and replies with 2 to the parent. The parent then send 0, 0 to the child. The child receives 0 and replies with a 0 and then exit. The parent
receives 0 and exits too.
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define SIZE 4096
#define NUM_OF_PIPES 2
#define P_READ 0
#define P_WRITE 1
#define C_READ 2
#define C_WRITE 3
int main(int argv, char *argc[]) {
/*Check if program is called correctly*/
if(argv != 3) {
printf("Please call program appropriately\n");
exit(EXIT_FAILURE);
}
FILE *r, *w, *check;
void *sharedMem;
int pipes[4];
int shm;
char userInput[5];
char *name = "dm11ad_cop4610";
int inChild = 0;
int inParent = 0;
r = fopen(argc[1], "rb");
check = fopen(argc[2], "rb");
/*Check if read file can open*/
if(r == NULL) {
perror("Error opening read file");
exit(EXIT_FAILURE);
}
/*Check if write file can open*/
if(check == NULL) {
perror("Error with write file");
exit(EXIT_FAILURE);
}
else {
fseek(check, 0, SEEK_END);
int writeLen = ftell(check);
if(writeLen > 0) {
rewind(check);
printf("Would you like to overwrite file (yes/no): ");
scanf("%s", userInput);
if(!strcmp(userInput, "yes")) {
printf("Overwriting file...\n");
w = fopen(argc[2], "wb");
}
else if(!strcmp(userInput, "no")) {
printf("Will not overwrite\n");
exit(EXIT_FAILURE);
}
else {
printf("User input not accepted\n");
exit(EXIT_FAILURE);
}
}
}
for (int i = 0; i < NUM_OF_PIPES; i++) {
if (pipe(pipes+(i*2)) < 0) {
perror("Pipe");
exit(EXIT_FAILURE);
}
}
/*Check if forking process is successful*/
pid_t pid = fork();
if(pid < 0) {
perror("Fork");
exit(EXIT_FAILURE);
}
shm = shm_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(shm == -1) {
perror("Shared memory");
exit(EXIT_FAILURE);
}
if(ftruncate(shm, SIZE) == -1) {
perror("Shared Memory");
exit(EXIT_FAILURE);
}
sharedMem = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0);
if(sharedMem == MAP_FAILED) {
perror("Mapping shared memory");
exit(EXIT_FAILURE);
}
if(pid == 0) {
while(inParent);
inChild = 1;
printf("I am in child\n");
close(pipes[P_READ]);
close(pipes[P_WRITE]);
printf("Closed P pipes\n");
int cBytes, len;
printf("Im stuck\n");
len = read(pipes[C_READ], &cBytes, sizeof(cBytes));
printf("There are %i bytes\n", len);
if(len < 0) {
perror("Failed to read from pipe");
exit(EXIT_FAILURE);
}
else if(len == 0) {
printf("End of fle reached\n");
}
else {
printf("Writing to file\n");
fwrite(sharedMem, 1, sizeof(sharedMem), w);
}
printf("Closing C pipes\n");
close(pipes[C_READ]);
close(pipes[C_WRITE]);
printf("Exiting Child\n");
inChild = 0;
}
else {
while(inChild);
inParent = 1;
close(pipes[C_READ]);
close(pipes[C_WRITE]);
int pBytes;
int P2SHM = fread(sharedMem, 1, SIZE, r);
if(P2SHM < 0) {
perror("Could not store to shared memory");
exit(EXIT_FAILURE);
}
if(write(pipes[P_WRITE], &P2SHM, sizeof(int)) < 0) {
perror("Failed to write to pipe");
exit(EXIT_FAILURE);
}
int C2P = read(pipes[P_READ], &pBytes, sizeof(int));
if(C2P < 0) {
perror("Failed to read value from pipe");
exit(EXIT_FAILURE);
}
else if(C2P == 0) {
printf("End of file reached\n");
}
else {
printf("Received succesfully\n");
}
close(pipes[P_READ]);
close(pipes[P_WRITE]);
inParent = 0;
printf("Waiting for child\n");
wait(NULL);
}
return 0;
}
The printfs are there to help me see where the program is during execution. It gets stuck in child process, it seems during
len = read(pipes[C_READ], &cBytes, sizeof(cBytes));
This is an assignment, so please do not post code as an answer but rather please hep me understand what I am doing wrong. Thanks
Synchronization mechanism between child and parent looks suspicious:
while(inParent);
inChild = 1;
and
while(inChild);
inParent = 1;
Initial values for inChild and inParent is 0. After child process created each process has it's own copy of variable values. When you change inChild = 1 and inParent = 1, it's changed inside the current process only. Other process doesn't see new values and cannot wait for the input/output.
To fix it you should use better synchronization algorithm, e.g. processes semaphores. Read "5.2 Processes Semaphores" to get details.
It gets stuck in child process, it seems during
len = read(pipes[C_READ], &cBytes, sizeof(cBytes));
Well yes, I imagine it does.
You've been a bit too clever, I think, in setting up a single 4-element array for the pipe-end file descriptors. That's not inherently wrong, but it tends to obscure what's going on a bit.
Consider what the pipes are supposed to do for you: one process writes to the write end of a pipe, and the other reads what was written from the read end of that same pipe. Look carefully at which file descriptors each process is reading from and writing to.

New to IPC, can't get my pipe to work

Sorry for the length of this post... I've encountered about a zillion problems in this. Up front I'll say I'm a student and my professor is a worthless resource. So, all I want to to do is have producer fork, then the parent producer will count some stuff in a file and send two ints to consumer, which was launched by the child process. I've tested everything, the fork and the file stuff works and I have printf statements all over the place so I know what is being done and where the code is at.
When I added the
if (pipe(pipefd) == -1) {
perror("pipe");
}
it caused my parent to just terminate. It reaches "parent pipe open" but then it dies. I checked with $ ps to see if it was just hung, but it's not there; it just dies. If I take that snippet out, it runs to the end but I presume if that code isn't there, then it's not actually aware that pipefd is a pipe... right?
I did search on this site and found another example of this and followed what he did as well as the answer and mine just refuses to work. I'm pretty sure it's a trivially easy thing to fix but I've run out of ideas of what to try :(
I don't really want to post all my code because it'll be a huge wall of text but I don't want to accidentally cut something out that turns out to be important either.
producer.c
#include <stdio.h> /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* _exit, fork, execl */
#include <stdlib.h> /* exit */
#include <errno.h> /* errno */
#include <string.h> /* strlen */
#include <sys/wait.h> /* wait */
#define SLEEP_TIME 8
int main (int argc, char *argv[]){
//PID
pid_t local_pid;
local_pid = fork();
//Logic to determine if the process running is the parent or the child
if (local_pid == -1) {
/* Error:
* When fork() returns -1, an error happened
* (for example, number of processes reached the limit).
*/
fprintf(stderr, "can't fork, error %d\n", errno);
exit(EXIT_FAILURE);
} else if (local_pid == 0) {
//Child specific code
int child;
char *temp[] = {NULL};
printf("Child PID found\n");
child = execv("./consumer", temp);
_exit(0);
} else {
//Parent specific code
printf("Parent running\n");
//open file
FILE * randStrings;
randStrings = fopen("randStrings.txt", "r");
int file_length;
int num_of_e = 0;
int c; //using this as a char
//until eof
while (feof(randStrings) == 0) {
c = fgetc(randStrings);
//calculate length of file
file_length++;
//count e chars
if (c == 'e') {
num_of_e++;
}
}
//close file
fclose(randStrings);
//send bundle to child
int a[2];
a[0] = num_of_e;
a[1] = file_length;
printf("num of e = %i\n", a[0]);
printf("len = %i\n", a[1]);
//set up parent pipe
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
printf("x\n");
}
printf("parent pipe open\n");
close(pipefd[0]); //close the read end
write(pipefd[1], &a[0], sizeof(int));
write(pipefd[1], &a[1], sizeof(int));
close(pipefd[1]);
printf("parent pipe closed\n");
//wait for child to finish running
wait(NULL);
printf("parent out\n");
//terminate
}
}
and consumer.c
#include <stdio.h> /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* _exit, fork, execl */
#include <stdlib.h> /* exit */
#include <errno.h> /* errno */
#define SLEEP_TIME 5
int main (int argc, char *argv[]){
sleep(SLEEP_TIME);
printf("Child program launched\n");
//receive bundle
int pipefd[2];
int buf[2];
if (pipe(pipefd) == -1) {
perror("pipe");
printf("child x\n");
}
close(pipefd[1]); //child closes write end
buf[0] = 0;
buf[1] = 0;
/*int i = 0; // i dont like this
while (read(pipefd[0], &buf[i], sizeof(int)) > 0) {
i++;
}*/
printf("child reading pipe\n");
read(pipefd[0], &buf[0], sizeof(int));
read(pipefd[0], &buf[1], sizeof(int));
close(pipefd[0]);
//buf should have the stuff in it
int num_of_e = buf[0];
int file_length = buf[1];
printf("child num of e = %i\n", num_of_e);
printf("child len = %i\n", file_length);
//open file
FILE * resultStrings;
resultStrings = fopen("resultStrings.txt", "w");
for (int i = 0; i < num_of_e; i++) {
//write num_of_e e chars
fputc('e', resultStrings);
}
//or if no e chars, write - chars
if (num_of_e == 0) {
for (int i = 0; i < file_length; i++) {
//write file_length '-' chars
fputc('-', resultStrings);
}
}
//close file
fclose(resultStrings);
printf("child out\n");
}
if you're still here after all that, you deserve a thank you just due to the length of this.
You're doing it wrong. The whole mechanism works because a child process inherits the parent's open file descriptors.
It should go like this:
Open the pipe with pipe(pipefd)
fork()
Parent (producer):
closes the read side (pipefd[0])
writes to the write side (pipefd[1])
Child (consumer):
closes the write side (pipefd[1])
reads from the read side (pipefd[0]) or calls exec
You are opening distinct pipes in both the parent and child process (after you've forked.) It needs to happen before you fork.
Now since you're execing, the new process needs to be aware of read-only pipe. There are a couple ways you could do this:
Pass it the file descriptor number (pipefd[0]) on the command line
dup2(1, fd) it to be the stdin of the newly exec'd process

Resources