设为首页 加入收藏

TOP

Linux下C程序插入执行shell脚本
2014-11-24 01:09:10 来源: 作者: 【 】 浏览:3
Tags:Linux 程序 插入 执行 shell 脚本

最近在看深入理解计算机系统,看到一个函数叫做execve(),这个函数很有意思,可以在一个进程插入另外一个进程执行,但是又不像fork()一样产生一个子进程,execve()插入的进程和原进程共享进程号,就好像执行这进程就像执行过程调用一般随意。


函数原型如下:


int execve(const char *filename, char *const argv[], char *const envp[]);



EXAMPLE
The following program is designed to be execed by the second program below. It just echoes its command-line one per line.


/* myecho.c */


#include
#include


int
main(int argc, char *argv[])
{
int j;


for (j = 0; j < argc; j++)
printf("argv[%d]: %s\n", j, argv[j]);


exit(EXIT_SUCCESS);
}


This program can be used to exec the program named in its command-line argument:


/* execve.c */


#include
#include
#include


int
main(int argc, char *argv[])
{
char *newargv[] = { NULL, "hello", "world", NULL };
char *newenviron[] = { NULL };


if (argc != 2) {
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}


newargv[0] = argv[1];


execve(argv[1], newargv, newenviron);
perror("execve"); /* execve() only returns on error */
exit(EXIT_FAILURE);
}


We can use the second program to exec the first as follows:


$ cc myecho.c -o myecho
$ cc execve.c -o execve
$ ./execve ./myecho
argv[0]: ./myecho
argv[1]: hello
argv[2]: world
插入一个shell脚本执行:



#include
#include
#include


int
main(int argc, char *argv[])
{
char *newargv[] = { "/etc" };
char *newenviron[] = { NULL };
if (argc != 2)
{
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}


newargv[0] = argv[1];


execve(argv[1], newargv, newenviron);
perror("execve"); /* execve() only returns on error */
exit(EXIT_FAILURE);
}
script.sh如下:


#!/bin/bash
ls 执行:


./execve ./script.sh


会在当前终端下输出所有的文件


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Cocos2d基础及基本函数 下一篇[SHELL] Linux流量监控脚本

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: