libin_v
asked on
How do U do redirection?
How do I get this code to redirect the output of ls to list.txt
/*
check for redirection
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int status;
pid = fork();
if (pid == 0)
{
int stdout = open ("list.txt", O_RDONLY);
dup2 (stdout, STDOUT_FILENO);
close (stdout);
execl ("\\bin\\ls", "ls", NULL);
}
if (pid == -1)
printf ("Error\n");
else
waitpid(pid, &status, 0);
}
/*
check for redirection
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int status;
pid = fork();
if (pid == 0)
{
int stdout = open ("list.txt", O_RDONLY);
dup2 (stdout, STDOUT_FILENO);
close (stdout);
execl ("\\bin\\ls", "ls", NULL);
}
if (pid == -1)
printf ("Error\n");
else
waitpid(pid, &status, 0);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
call to open() is wrong
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int status;
pid = fork();
if (pid == 0)
{
int stdout = open ("list.txt", O_WRONLY | O_CREAT); // use this
dup2 (stdout, STDOUT_FILENO);
close (stdout);
execl ("\\bin\\ls", "ls", NULL);
}
if (pid == -1)
printf ("Error\n");
else
waitpid(pid, &status, 0);
}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int status;
pid = fork();
if (pid == 0)
{
int stdout = open ("list.txt", O_WRONLY | O_CREAT); // use this
dup2 (stdout, STDOUT_FILENO);
close (stdout);
execl ("\\bin\\ls", "ls", NULL);
}
if (pid == -1)
printf ("Error\n");
else
waitpid(pid, &status, 0);
}
maybe... I don't know if that's ok...
baboo_