Here is the full code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
char *command, *infile, *outfile;
int wstatus;
command = argv[1];
infile = argv[2];
outfile = argv[3];
if (fork()) {
wait(&wstatus);
printf("Exit status: %d\n", WEXITSTATUS(wstatus));
}
else {
close(0);
open(infile, O_RDONLY);
close(1);
open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
execlp(command, command, NULL);
}
return 0;
}
This code should fork and exec a command with both stdin and stdout redirection, then wait for it to terminate and printf WEXITSTATUS(wstatus) received. e.g. ./allredir hexdump out_of_ls dump_file.
So, I understand everything before fork(). But I have the following questions:
As far as I understand, fork() clones the process, however I do not understand how it executes the command, because execlp should do that and code never reaches that part.
I do not get how execlp works. Why do we send a command to it twice (execlp(command, command, NULL);)?
How does execlp know where to redirect the output if we do not pass outfile nowhere.
Why do we even need an infile if the command is already passed as the other argument?
Thank you for your answers in advance.
As far as I understand, fork() clones the process, however I do not understand how it executes the command, because execlp should do that
and code never reaches that part.
Fork returns pid of child in parent space and 0 in new process space. The son process makes a call to execlp.
if (fork()) {
/* Parent process waits for child process */
}
else {
/* Son process */
execlp(command, command, NULL);
}
I do not get how execlp works. Why do we send a command to it twice
(execlp(command, command, NULL);)?
Read execlp man page and this thread
The first argument, by convention, should point to the filename
associated with the file being executed.
How does execlp know where to redirect the output if we do not pass outfile nowhere.
Redirection happens before by closing stdin and stdout file descriptors. And redirection happens by opening files which file descriptors will accommodate entries 0 and 1.
else {
/* redirecting stdin */
close(0);
open(infile, O_RDONLY);
/* redirecting stdout */
close(1);
open(outfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
execlp(command, command, NULL);
}
Why do we even need an infile if the command is already passed as the other argument?
We can't tell what your program does without seeing the argument passed as command.
Related
I am trying to do the equivalent of the bash command ls>foo.txt in C.
The code bellow redirects the output to a variable.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
close(pfds[0]);
//close(1);//Close stdout
//dup(pfds[1]);
//execlp("ls", "ls", NULL);
write(pfds[1], "test", 5); //Writing in the pipe
exit(0);
} else {
close(pfds[1]);
read(pfds[0], buf, 5); //Read from pipe
wait(NULL);
}
return 0;
}
The comments lines refer to those operations that I believe that are required for the redirection.
What should I change to redirect the output of ls to foo.txt?
While dealing with redirecting output to a file you may use freopen().
Assuming you are trying to redirect your stdout to a file 'output.txt' then you can write-
freopen("output.txt", "a+", stdout);
Here "a+" for append mode. If the file exists then the file open in append mode. Otherwise a new file is created.
After reopening the stdout with freopen() all output statement (printf, putchar) are redirected to the 'output.txt'. So after that any printf() statement will redirect it's output to the 'output.txt' file.
If you want to resume printf()'s default behavior again (that is printing in terminal/command prompt) then you have to reassign stdout again using the following code-
freopen("/dev/tty", "w", stdout); /*for gcc, ubuntu*/
Or -
freopen("CON", "w", stdout); /*Mingw C++; Windows*/
However similar technique works for 'stdin'.
What your code essentially does is that you open a pipe, then fork the process and in the child process (in commented code) close stdout, duplicate the pipe to stdout and execute and ls command, and then (in non-commented code) write 4 bytes to the pipe. In the parent process, you read data from the pipe and wait for the completion of the child process.
Now you want to redirect stdout to a file. You can do that by opening a file using the open() system call and then duplicating that file descriptor to stdout. Something like (I haven't tested this so beware of bugs in the code):
int filefd = open("foo.txt", O_WRONLY|O_CREAT, 0666);
if (!fork()) {
close(1);//Close stdout
dup(filefd);
execlp("ls", "ls", NULL);
} else {
close(filefd);
wait(NULL);
}
return 0;
However, you can also use the freopen as suggested by the other answer.
However, I have several concerns of your code and of my modified code:
The pipe() and open() system calls can fail. You should always check for system call failure.
The fork() system call can fail. Ditto.
dup2() can be used instead of dup(); otherwise the code will fail if stdin is not open as it duplicates to the first available file descriptor.
The execlp() system call can fail. Ditto.
I think wait() can be interrupted by a signal (EINTR). It's recommended to wrap it around a wrapper that retries the system call if it's aborted by a signal (errno == EINTR).
I am trying to do the equivalent of the bash command ls>foo.txt in C.
The code bellow redirects the output to a variable.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
close(pfds[0]);
//close(1);//Close stdout
//dup(pfds[1]);
//execlp("ls", "ls", NULL);
write(pfds[1], "test", 5); //Writing in the pipe
exit(0);
} else {
close(pfds[1]);
read(pfds[0], buf, 5); //Read from pipe
wait(NULL);
}
return 0;
}
The comments lines refer to those operations that I believe that are required for the redirection.
What should I change to redirect the output of ls to foo.txt?
While dealing with redirecting output to a file you may use freopen().
Assuming you are trying to redirect your stdout to a file 'output.txt' then you can write-
freopen("output.txt", "a+", stdout);
Here "a+" for append mode. If the file exists then the file open in append mode. Otherwise a new file is created.
After reopening the stdout with freopen() all output statement (printf, putchar) are redirected to the 'output.txt'. So after that any printf() statement will redirect it's output to the 'output.txt' file.
If you want to resume printf()'s default behavior again (that is printing in terminal/command prompt) then you have to reassign stdout again using the following code-
freopen("/dev/tty", "w", stdout); /*for gcc, ubuntu*/
Or -
freopen("CON", "w", stdout); /*Mingw C++; Windows*/
However similar technique works for 'stdin'.
What your code essentially does is that you open a pipe, then fork the process and in the child process (in commented code) close stdout, duplicate the pipe to stdout and execute and ls command, and then (in non-commented code) write 4 bytes to the pipe. In the parent process, you read data from the pipe and wait for the completion of the child process.
Now you want to redirect stdout to a file. You can do that by opening a file using the open() system call and then duplicating that file descriptor to stdout. Something like (I haven't tested this so beware of bugs in the code):
int filefd = open("foo.txt", O_WRONLY|O_CREAT, 0666);
if (!fork()) {
close(1);//Close stdout
dup(filefd);
execlp("ls", "ls", NULL);
} else {
close(filefd);
wait(NULL);
}
return 0;
However, you can also use the freopen as suggested by the other answer.
However, I have several concerns of your code and of my modified code:
The pipe() and open() system calls can fail. You should always check for system call failure.
The fork() system call can fail. Ditto.
dup2() can be used instead of dup(); otherwise the code will fail if stdin is not open as it duplicates to the first available file descriptor.
The execlp() system call can fail. Ditto.
I think wait() can be interrupted by a signal (EINTR). It's recommended to wrap it around a wrapper that retries the system call if it's aborted by a signal (errno == EINTR).
I am trying to do the equivalent of the bash command ls>foo.txt in C.
The code bellow redirects the output to a variable.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
close(pfds[0]);
//close(1);//Close stdout
//dup(pfds[1]);
//execlp("ls", "ls", NULL);
write(pfds[1], "test", 5); //Writing in the pipe
exit(0);
} else {
close(pfds[1]);
read(pfds[0], buf, 5); //Read from pipe
wait(NULL);
}
return 0;
}
The comments lines refer to those operations that I believe that are required for the redirection.
What should I change to redirect the output of ls to foo.txt?
While dealing with redirecting output to a file you may use freopen().
Assuming you are trying to redirect your stdout to a file 'output.txt' then you can write-
freopen("output.txt", "a+", stdout);
Here "a+" for append mode. If the file exists then the file open in append mode. Otherwise a new file is created.
After reopening the stdout with freopen() all output statement (printf, putchar) are redirected to the 'output.txt'. So after that any printf() statement will redirect it's output to the 'output.txt' file.
If you want to resume printf()'s default behavior again (that is printing in terminal/command prompt) then you have to reassign stdout again using the following code-
freopen("/dev/tty", "w", stdout); /*for gcc, ubuntu*/
Or -
freopen("CON", "w", stdout); /*Mingw C++; Windows*/
However similar technique works for 'stdin'.
What your code essentially does is that you open a pipe, then fork the process and in the child process (in commented code) close stdout, duplicate the pipe to stdout and execute and ls command, and then (in non-commented code) write 4 bytes to the pipe. In the parent process, you read data from the pipe and wait for the completion of the child process.
Now you want to redirect stdout to a file. You can do that by opening a file using the open() system call and then duplicating that file descriptor to stdout. Something like (I haven't tested this so beware of bugs in the code):
int filefd = open("foo.txt", O_WRONLY|O_CREAT, 0666);
if (!fork()) {
close(1);//Close stdout
dup(filefd);
execlp("ls", "ls", NULL);
} else {
close(filefd);
wait(NULL);
}
return 0;
However, you can also use the freopen as suggested by the other answer.
However, I have several concerns of your code and of my modified code:
The pipe() and open() system calls can fail. You should always check for system call failure.
The fork() system call can fail. Ditto.
dup2() can be used instead of dup(); otherwise the code will fail if stdin is not open as it duplicates to the first available file descriptor.
The execlp() system call can fail. Ditto.
I think wait() can be interrupted by a signal (EINTR). It's recommended to wrap it around a wrapper that retries the system call if it's aborted by a signal (errno == EINTR).
I tried popen() and it is working well for output with "r" passed as a second argument; I know you can use "w" as writing mode and it worked for me (the program was just one scanf()). My question is how to use the append ("a") mode. You can both write and read, how do you know when the program is outputting something and when it's requesting for user input?
popen uses a pipe (that's the "p" in "popen") and pipes are unidirectional. You can either read or write from one end of a pipe, not both. To get both read/write access you should use a socketpair instead. I use this in my programs when I want something like popen, but for read/write:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
FILE *sopen(const char *program)
{
int fds[2];
pid_t pid;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0)
return NULL;
switch(pid=vfork()) {
case -1: /* Error */
close(fds[0]);
close(fds[1]);
return NULL;
case 0: /* child */
close(fds[0]);
dup2(fds[1], 0);
dup2(fds[1], 1);
close(fds[1]);
execl("/bin/sh", "sh", "-c", program, NULL);
_exit(127);
}
/* parent */
close(fds[1]);
return fdopen(fds[0], "r+");
}
Note that since it doesn't return the child's pid, you'll have a a zombie process after the child program exits. (Unless you set up SIGCHLD...)
I'm trying to implement unix piping in c (i.e. execute ls | wc). I have found a related solution to my problem (C Unix Pipes Example) however, I am not sure why a specific portion of the solved code snippet works.
Here's the code:
/* Run WC. */
int filedes[2];
pipe(filedes);
/* Run LS. */
pid_t pid = fork();
if (pid == 0) {
/* Set stdout to the input side of the pipe, and run 'ls'. */
dup2(filedes[1], 1);
char *argv[] = {"ls", NULL};
execv("/bin/ls", argv);
} else {
/* Close the input side of the pipe, to prevent it staying open. */
close(filedes[1]);
}
/* Run WC. */
pid = fork();
if (pid == 0) {
dup2(filedes[0], 0);
char *argv[] = {"wc", NULL};
execv("/usr/bin/wc", argv);
}
In the child process that executes the wc command, though it attaches stndin to a file descriptor, it seems that we are not explicitly reading the output produced by ls in the first child process. Thus, to me it seems that ls is run independently and wc is running independently as we not explicitly using the output of ls when executing wc. How then does this code work (i.e. it executes ls | wc)?
The code shown just about works (it cuts a number of corners, but it works) because the forked children ensure that the the file descriptor that the executed process will write to (in the case of ls) and read from (in the case of wc) is the appropriate end of the pipe. You don't have to do any more; standard input is file descriptor 0, so wc with no (filename) arguments reads from standard input. ls always writes to standard output, file descriptor 1, unless it is writing an error message.
There are three processes in the code snippet; the parent process and two children, one from each fork().
The parent process should be closing both its ends of the pipe too; it only closes one.
In general, after you do a dup() or dup2() call on a pipe file descriptor, you should close both ends of the pipe. You get away with it here because ls generates data and terminates; you wouldn't in all circumstances.
The comment:
/* Set stdout to the input side of the pipe, and run 'ls'. */
is inaccurate; you're setting stdout to the output side of the pipe, not the input side.
You should have an error exit after the execv() calls; if they fail, they return, and the process can wreak havoc (for example, if the ls fails, you end up with two copies of wc running.
An SSCCE
Note the careful closing of both ends of the pipe in each of the processes. The parent process has no use for the pipe once it has launched both children. I left the code which closes filedes[1] early in place (but removed it from an explicit else block since the following code was also only executed if the else was executed). I might well have kept pairs of closes() in each of the three code paths where files need to be closed.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int filedes[2];
int corpse;
int status;
pipe(filedes);
/* Run LS. */
pid_t pid = fork();
if (pid == 0)
{
/* Set stdout to the output side of the pipe, and run 'ls'. */
dup2(filedes[1], 1);
close(filedes[1]);
close(filedes[0]);
char *argv[] = {"ls", NULL};
execv("/bin/ls", argv);
fprintf(stderr, "Failed to execute /bin/ls\n");
exit(1);
}
/* Close the input side of the pipe, to prevent it staying open. */
close(filedes[1]);
/* Run WC. */
pid = fork();
if (pid == 0)
{
/* Set stdin to the input side of the pipe, and run 'wc'. */
dup2(filedes[0], 0);
close(filedes[0]);
char *argv[] = {"wc", NULL};
execv("/usr/bin/wc", argv);
fprintf(stderr, "Failed to execute /usr/bin/wc\n");
exit(1);
}
close(filedes[0]);
while ((corpse = waitpid(-1, &status, 0)) > 0)
printf("PID %d died 0x%.4X\n", corpse, status);
return(0);
}
Example output:
$ ./pipes-14312939
32 32 389
PID 75954 died 0x0000
PID 75955 died 0x0000
$