开发者

UNIX run program within another program

I am trying to execute a program from within a C program (inside UNIX).

I have been given an executable ( the program requires a string input during execution and writes that input to another file called sample ) called exec and I want to execute it in program.c, but giving the string input through indirection.

For that I created a file as follows:

% vim input

I wrote the following inside the input file

content

Now in program.c,

#include<unistd.h>
int main()
{
      const char* command = "./exec < input";
      execvp(command, NULL);
      return 0;
}

When I run the pr开发者_如何学编程ogram, the content is not entered into the sample file.

But when I run it without indirection, i.e.

const char* command = "./exec";

then it works, and input entered in saved in sample file.

Can someone please tell what am I doing wrong in the indirection syntax.

Thanks.


The syntax you are using is supposed to be interpreted by a shell like bash, csh, ksh, etc.

The system call execvp only expects the path to the executable and a number of arguments, the shell is not invoked there.

To perform redirection in this manner, you'll have to use the dup2(2) system call before calling execvp:

int fd = open("input", O_RDONLY);
/* redirect standard input to the opened file */
dup2(fd, 0);
execvp("/path/to/exec", ...);

Of course, you'll need some additional error checking in a real-world program.


You can't do redirection like that with execvp. Use system() or start getting friendly with dup() and friends. You might google 'implementing redirection'.. you'll likely turn up plenty of examples of how shells (for example) handle this problem.


The exec(3) family of functions does not know anything about input redirection or parsing command lines: it tries to execute exactly the executable you give it. It's trying to search for an executable file with the name "./exec < input", which unsurprisingly does not exist.

One solution would be to use the system(3) function instead of exec. system invokes the user's shell (such as /bin/bash), which is capable of parsing the command line and doing appropriate redirections. But, system() is not as versatile as exec, so it may or may not be suitable for your needs.

The better solution is to do the input redirection yourself. What you need to do us use open(3) to open the file and dup2(3) to duplicate the file descriptor onto file descriptor 0 (standard input), and then exec the executable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜