简体   繁体   中英

How to redirect the IO of child process created by fork() and uses exec() function?

I am writing a Shell in C language. User should be able to execute various commands and use pipe(|) to redirect input of one command to the other. The main shell process is the parent process and forks new process for each command and in child process the command is called by exec*() function.

But I can't figure out how to redirect the Standard input/output of one child process to the other.

May be this can help you....

int f=open(somefile, O_WRONLY | O_CREAT, S_IRWXU);
dup2(f,1);  //redirecting output to file
//execute your first command here using fork
close(f);
int f=open(somefile, O_RDONLY | O_CREAT, S_IRWXU);
dup2(f,0);    //this will give the ouput of the first command to stdout 
//i.e. the input is present for second one
//execute your second command here
close(f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM