【发布时间】:2011-06-17 23:42:30
【问题描述】:
试图实现一个外壳,主要是管道。我已经编写了这个测试用例,我希望它可以简单地将 ls 传输到 wc ......它绝对不能按预期工作。它将 ls 打印到终端,然后打印内存耗尽。 我非常迷茫如何解决这个问题并让它工作。 find_path 在我的所有测试中都有效。
编辑 - 我必须对项目使用 execv,它是一个类的东西,但我已经尝试使用 execvp 以防万一,它做的事情完全相同。这也只是一个例子,一个测试它为什么不起作用的测试,我为两个命令和 waitpid 调用了两次 fork 一次,因为我没有别的事可做。
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int find_path(char* execname, char** dst)
{
char *path = getenv("PATH");
path = strdup(path);
char *pos;
path = strtok_r(path, ":", &pos);
char *originalpath = path;
do
{
char* test = (char*)calloc(strlen(path) + strlen(execname) + 2, sizeof(char));
test = strcpy(test, path);
int testlen = strlen(test);
(*(test+testlen)) = '/';
strcpy(test + testlen + 1,execname);
struct stat buf;
int result = stat(test, &buf);
if (result == 0)
{
*dst = test;
free (originalpath);
return 1;
}
else
{
free(test);
}
} while ((path = strtok_r(NULL, ":", &pos)) != NULL);
free(originalpath);
return 0;
}
int main()
{
char *cmd1 = "ls";
char *cmd2 = "wc";
int filedes[2];
pipe(filedes);
char** argv = (char**)calloc(1, sizeof(char*));
argv[0] = (char*)malloc(sizeof(char*));
argv[0] = NULL;
pid_t pid = fork();
if (pid == 0)
{
char *path;
find_path(cmd1, &path);
dup2(filedes[1],stdout);
execv(path,argv);
}
pid = fork();
if (pid == 0)
{
dup2(filedes[0], stdin);
char *path;
find_path(cmd2, &path);
execv(path, argv);
}
else
waitpid(pid);
}
【问题讨论】:
-
您是否看过去年“如何使用 ... fork ... pipe ... exec ... 实现 shell”问题?答案可能在其中一个(更可能是多个)中。