char *ar[]={"ls",">","mylog.dat"};
execv("ls",ar);
I'm going to kill this guy. He dont know what is the difference between passing argument to a command and output redirection. And also dont know who is doing the redirection.
when you say,
ls -l > mylog.dat
this is what shell does
1. Shell forks itself
2. Close the stdout of the child process
3. Open the file and bind it with the stdout of the child process
4. execl "ls -l" on child process
5. parent process (i.e. shell) waits till the complete execution of the child process
Program 1:
#include <unistd.h>
#include <fcntl.h>
int main() {
char *ar[]={"ls","-l"};
int fd;
close(1);
fd=open("/users/revincen/cpp/sample.dat",O_CREAT|O_WRONLY);
write(1,"hello world\n",12);
execv("/bin/ls",ar);
return 0;
}
Program 2:
#include <stdio.h>
#include <stdlib.h>
int main() {
char buf[256];
FILE *inp,*outp;
inp = popen("ls -l","r");
outp=fopen("hello.dat","w");
while ( fgets(buf,sizeof buf,inp) != 0 )
fputs(buf,outp);
pclose(inp);
return 0;
}
No comments:
Post a Comment