C程序调用shell脚本共有三种方式:system()、popen()、exec系列函数
1)system(shell命令或shell脚本路径);
2)popen(char *command,char *type)
例:C程序popentest.c内容如下:
履行 效果 如下:
[root@localhost test]$ vim popentest.c
[root@localhost test]$ gcc popentest.c -o popentest
[root@localhost test]$ ./popentest
/root/test
[root@localhost test]$
(3)exec用被执行的程序完全替换调用它的程序的影像。fork创建一个新的进程就产生了一个新的PID,exec启动一个新程序,替换原有的进程,因此这个新的被exec执行的进程的PID不会改变,和调用exec函数的进程一样。
程序例:
/* execv example */
#include <process.h>
#include <stdio.h>
#include <errno.h>
void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%2d] : %s\n", i, argv[i]);
printf("About to exec child with arg1 arg2 ...\n");
execv("CHILD.EXE", argv);
perror("exec error");
exit(1);
}