因此,我试图在C中复制管道的功能,当使用dup2将管道用作输出时,程序将停止工作.它不会崩溃,只是有点冻结.我不认为我做错了什么...
这是子函数-
void child(t_pipex pipex, char *cmd)
{
int i;
int err;
char *temp_path;
i = 0;
printf("Child: made it to my function\n");
printf("Child: fd1 = %d\n", pipex.fd1);
printf("Child: tube[1] = %d\n", pipex.tube[1]);
err = dup2(pipex.tube[1], STDOUT_FILENO);
printf("Child: dup2 (1): %d\n", err);
close(pipex.tube[0]);
printf("Child: First dup2 worked\n");
dup2(pipex.fd1, 0);
printf("Child: Second dup2 worked\n");
pipex.split_cmd = ft_split(cmd, ' ');
while (pipex.all_paths[i])
{
temp_path = ft_join(pipex.all_paths[i], pipex.split_cmd[0]);
if(access(temp_path, F_OK | X_OK) == 0)
{
printf("Child: access success\n");
err = execve(temp_path, &pipex.split_cmd[1], pipex.environment);
if (err == -1)
{
printf("Child: error...\n");
free(temp_path);
perror("child execve");
}
}
i++;
}
printf("Child: closing pipe...\n");
close(pipex.tube[1]);
}
调用my child函数的函数-
void ft_pipex(t_pipex pipex, char **argv)
{
int spoon;
spoon = fork();
if (spoon < 0)
perror("Fork:");
if (spoon == 0)
{
//CHILD
pipex.pid1 = spoon; //I THINK
child(pipex, argv[2]);
}
else
{
//PARENT
pipex.pid2 = spoon; //I THINK
parent(pipex, argv[3]);
}
}
和我的主要功能-
int main(int argc, char **argv, char **envp)
{
t_pipex pipex;
if (argc != 5)
{
printf("Please use only 4 arguments\n");
//printf("infile command1 command2 outfile\n");
return (0);
}
if (pipe(pipex.tube) < 0)
perror("Pipe");
pipex.path = (string_finder(envp, "PATH=") + 5);
pipex.all_paths = ft_joinall(ft_split(pipex.path, ':'), "/");
pipex.fd1 = open(argv[1], O_RDONLY);
pipex.fd2 = open(argv[4], O_CREAT | O_RDWR | O_TRUNC, 0644);
pipex.environment = envp;
ft_pipex(pipex, argv);
}
t_pipex如下:
typedef struct s_pipex
{
int tube[2];
int fd1;
int fd2;
int pid1;
int pid2;
char *path;
char **all_paths;
char **split_cmd;
char **environment;
} t_pipex;
输出...
Child: made it to my function
Child: fd1 = 5
Child: tube[1] = 4
A NULL argv[0] was passed through an exec system call.
^C
无论我是否注释掉dup2,都会出现空argv [0].我把什么地方搞砸了吗?
抱歉之前的错误,这是我的第一个帖子,我真的不知道我在做什么.谢谢