简体   繁体   中英

Create C program that runs and passes batched commands to a second C program

Thanks in advance for the help.

I'm relatively new to C and would like to accomplish the following task. I have a C program that takes a series of console inputs until a termination command is given. For example

./myCProg  //runs myCProg in console
do this
do that
.....
quit // terminates program

I have a file containing a series of commands that I would like to run in the format given above. I would like to create a second C program that will run the C program given above and pass to it the commands in the file to speed things up. For the most part, I know how to do this. However, how might I run the first C program within the second and pass commands to it?

In your second program, open the input file for reading with open , then fork() . In the forked process, use dup2 to duplicate the file descriptor for the input file to file descriptor 0, then use an exec function to call the first program.

The result is that the first program is running with the input file connected to its stdin, just as if you ran ./prog1 < input_file from the command line.

int fd = open("input_file", O_RDONLY);
if (fd == -1) {
    perror("open failed");
    exit(1);
}
pid_t pid = fork();
if (pid == -1) {
    perror("fork failed");
    exit(1);
} else if (pid == 0) {
    dup2(fd, 0);
    execl("/path/to/prog1", "prog1", NULL);
    perror("exec failed");
    exit(1);
}

(What you want to achieve is unclear; I'm just guessing; and it is operating system specific; I guess you are using Linux or some other POSIX)

It seems similar to some shell. You might take inspiration from the code of existing shells (like bash , sash , zsh , fish ...)

Alternatively, embed some existing interpreter (like Guile or Lua ...) in your top C program.

BTW, to run a command from C, consider system(3) or popen(3) ; for example, you might popen("/bin/sh", "w") and fprintf some shell commands, then pclose

Probably, you need to get a broad picture by reading advanced linux programming then see syscalls(2) (notably fork(2) , pipe(2) , dup2(2) , execve(2) , ....)

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