dup2(filedescriptor, STDOUT_FILENO) 是否会干扰写入和读取?

问题描述

我已经编写了这个程序

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <fcntl.h>


void redirect(char* filename,char* temp){
  chdir("/Users/.....my name..../Desktop");
  char buff1[1024];
  int fd1,fd2;
  if ((fd1 = open(filename,O_RDONLY,S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH)) == -1){
    perror("file problem thomas");
    exit(1);
  }
  if ((fd2 = open(temp,O_RDWR | O_CREAT | O_APPEND,S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH)) == -1){
    perror("file problem temp");
    exit(1);
  }
  int r = read(fd1,buff1,1024);
  write(fd2,r);
  dup2(fd2,STDOUT_FILENO);
  char *args[] = {"ls",NULL};
  execvp(args[0],args);
  dup2(STDOUT_FILENO,fd2);
  
  close(fd1);
  close(fd2);
}
void copy_file(char* filename,char* temp){
  chdir("/Users/.....my name ..../Desktop");
  int fd1,fd2;
  char buffer[1024];
  long int n1;
  if ((fd1 = open(temp,O_RDONLY))==-1 || ((fd2 = open(filename,O_WRONLY|O_CREAT)) == -1)){
    perror("file problem");
    exit(1);
  }
  printf("fd1: %d\n",fd1);
  printf("fd2: %d\n",fd2);  
  while((n1 = read(fd1,buffer,1024)) > 0){
    if (write(fd2,n1) != n1){
      perror("writing problem");
      exit(3);
    }
  }
  close(fd1);
  close(fd2);
}

int main(){
  redirect("thomas","TEMP");
  copy_file("thomas","TEMP");
}

我有两个文件“thomas”和“TEMP”。我想要做的是将“thomas”的内容写入“TEMP”,然后将命令行上“ls”的输出写入“TEMP”,然后将整个“TEMP”文件写回“thomas” ”。出于某种原因,当我同时运行这两个文件时, copy_file 函数不会运行 - 只有重定向会。但是,当我在没有重定向(...)的情况下运行此程序时,copy_file 函数会起作用。

为什么 copy_file 没有与重定向一起运行? 这是否与我运行 dup2(STDOUT_FILENO,fd2) 然后不更改 STDOUT 文件描述符有关?

感谢任何帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)