在linux中,我想编写一个启动另一个程序的C程序。当程序运行时,shell 将等待您输入您在程序中定义的命令。该命令将启动第二个程序。
例如,假设在与调用程序相同的目录中有一个名为“hello”的简单 C 程序。 “hello”程序打印输出“hello, world”。第一个程序将运行,用户将输入命令“hello”。 “hello”程序将被执行,“hello,world”。将输出到 shell。
我做了一些搜索,人们建议使用“fork()”和“exec()”函数。其他人说使用“system()”。我对这些功能一无所知。我如何调用这些函数?它们适合使用吗?
带有解释的示例代码将是最有帮助的。也欢迎其他答案。非常感谢您的帮助。
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)