dup2

Pipes, dup2 and exec()

故事扮演 提交于 2019-11-26 21:25:37
问题 I have to write a shell that can run pipes. For example commands like ls -l | wc -l ". I have successfully parsed the command given by the user as below: "ls" = firstcmd "-l" = frsarg "wc" = scmd "-l" = secarg Now I have to use two forks since the commands are two and a pipe. The code block that I wrote to exec the command is the following: pid_t pid; int fd[2]; pipe(fd); pid = fork(); if(pid==0) { dup2(fd[WRITE_END], STDOUT_FILENO); close(fd[READ_END]); execlp(firstcmd, firstcmd, frsarg,

Using dup2 for piping

僤鯓⒐⒋嵵緔 提交于 2019-11-26 15:33:35
问题 How do I use dup2 to perform the following command? ls -al | grep alpha | more 回答1: A Little example with the first two commands. You need to create a pipe with the pipe() function that will go between ls and grep and other pipe between grep and more. What dup2 does is copy a file descriptor into another. Pipe works by connecting the input in fd[0] to the output of fd[1]. You should read the man pages of pipe and dup2. I may try and simplify the example later if you have some other doubts.

Can popen() make bidirectional pipes like pipe() + fork()?

谁都会走 提交于 2019-11-26 08:11:02
问题 I\'m implementing piping on a simulated file system in C++ (with mostly C). It needs to run commands in the host shell but perform the piping itself on the simulated file system. I could achieve this with the pipe() , fork() , and system() system calls, but I\'d prefer to use popen() (which handles creating a pipe, forking a process, and passing a command to the shell). This may not be possible because (I think) I need to be able to write from the parent process of the pipe, read on the child