【发布时间】:2012-09-25 03:30:28
【问题描述】:
到目前为止,我唯一感到困惑的部分是如何使用第一个参数设置 execv 作为当前工作目录。我已经尝试了两个“。”和“~”,都没有对屏幕执行任何操作; “/”也一样。和“/~”。我对如何让 execv 运行这样的事情感到困惑:
$ ./prog ls -t -al
并让它在当前目录或与文件所在目录相同的目录中执行程序执行后的命令(存储在argv中)(根据使用者的不同而有所不同。)
我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main(int argc, char *argv[])
{
int pid;
int count = 0;
char *argv2[argc+1];
for(count = 0; count < argc-1; count++){
argv2[count] = argv[count+1];
printf("Argv2: %s\n", argv2[count]); //just double checking
argv2[argc-1] = NULL;
}
pid = fork();
if(pid == 0){
printf("Child's PID is %d. Parent's PID is %d\n", (int)getpid, (int)getppid());
execv(".", argv2); //<---- confused here
}
else{
wait(pid);
exit(0);
}
}
一些示例输出:
$ ./prog ls -t -al
Argv2: ls
Argv2: -t
Argv2: -al
Child's PID is 19194. Parent's PID is 19193
【问题讨论】:
-
我建议增加“编译器警告”的设置。它应该告诉你从 main 返回 int。在我的系统上,它还抱怨缺少#include
。并且 wait 将整数指针作为参数,而不是整数。