0

我正在尝试通过父进程获取命令并在不同的进程(子进程)中执行它。

#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<malloc.h>

int main(){
 pid_t pid = -1;
 int status = -1;
 char* ip = malloc(20);
 char* a[20];
 int pd[2];
 char* path = NULL;

 path = getenv("PATH");
 printf("\n path : %s \n",path);

 a[0] = malloc(10);

 while(1){
  pipe(pd);
  pid = fork();
  if(pid == 0){
   //printf("\n Child! - pid : %d \n",getpid());
   sleep(1);
   close(pd[1]);
   read(pd[0],ip,20);
   a[0] = ip;
   //execl(ip,ip,NULL);
   execv(path,a);
   exit(0);
  }
  else{
   //printf("\n Parent! - pid : %d \n",getpid());
   printf("(Enter a executable)$  ");
   scanf("%s",ip);
   //printf("\n %s \n",ip);
   close(pd[0]);
   write(pd[1],ip,20);
   waitpid(pid,&status,0);
   //printf("\n The child %d exited with status : %d \n",pid,status);
  }
 }
 free(ip);
 return 0;
}

路径和环境有什么区别。getenv 函数为我提供了可执行文件的整个路径。上面的程序没有执行命令 ls -l。

我想执行命令 ls -l 并且输出应该显示在屏幕上,并且应该存储在一个文件中。我尝试执行命令 ls -l。但它没有执行。当它在屏幕上输出时,有没有办法将 ls -l 输出到文件中?

4

2 回答 2

1

yes, there is a way to output to the screen and to a file at the same time, it is called tee.

    ls -l | tee your_output_file
于 2013-09-26T03:00:02.043 回答
0

您运行execv(path,a),使用path作为第一个参数,但您已设置pathPATH环境变量的内容。PATH是 shell 搜索可执行文件的目录列表;第一个参数execv应该是要调用的可执行文件的路径。(或者,execlp其他一些变体可以搜索 `PATH` 环境变量。)

您的代码还有其他一些问题。看起来输入的全部内容都被用作程序的名称(例如,它会查找名称为“ls -l”的五个字符的可执行文件),并且会因长度超过约 20 个字符的命令而中断。

于 2013-09-26T03:37:43.727 回答