Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

linux - How do you write a C program to execute another program?

In linux, I would like to write a C program that launches another program. When the program runs, the shell will be waiting for you to input a command that you have defined in you program. This command will launch the second program.

For example, assume there is a simple C program called "hello" in the same directory as the invoking program. The "hello" program prints the output "hello, world". The first program would be run and the user would input the command "hello." The "hello" program would be executed and "hello, world." would be output to the shell.

I have done some search, and people suggested the "fork()" and "exec()" functions. Others said to use "system()". I have no knowledge about these functions. How do I call these functions? Are they appropriate to use?

Example code with explanations would be most helpful. Other answers are also welcome. Your help is greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */

int main()
{
    /*Spawn a child to run the program.*/
    pid_t pid=fork();
    if (pid==0) { /* child process */
        static char *argv[]={"echo","Foo is my name.",NULL};
        execv("/bin/echo",argv);
        exit(127); /* only if execv fails */
    }
    else { /* pid!=0; parent process */
        waitpid(pid,0,0); /* wait for child to exit */
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...