简体   繁体   中英

File descriptors not properly passed to processes generated with execve() system call

I'm reading a unix book and specifically the part about execve() system call. The book says that file descriptors related to opened file are passed to child processes and also ( default behaviour ) after a process calls execve().

However, when I tried this code to read an opened file descriptor delivered to a process generated with execve() it doesn't seem to work. What's the problem ?

Program that calls execve() :



  int main(int arg,char *argv[],char **env){


  int fd;
  if ( (fd = open("text.txt",O_RDWR | O_CREAT, ALL_OWNER )) == -1 ){
       printf("Open failed\n");
       exit(1);
       
  };
  printf("%d\n",fd); // 3


  char buff [] = "Hello World\n";
  write(fd,buff,strlen(buff));
  int res;
  if ( (res = execl("./demo",(char *)0)) == -1 ){
        exit(1);
  };
    

 }

Program demo invoked by execve() :


  setbuf(stdout,NULL);
  printf("Demo executing...\n");
  ssize_t r;
  char buff[1024];
  while ( (r = read(3,buff,sizeof(buff))) > 0 ){
           write(STDOUT_FILENO,buff,r);
  }

  • I'm using a Mac OS

The "demo" process inherit file descriptor and can read the file, but the file offset is at the end of the file. Use lseek(fd, 0, SEEK_SET) before calling execl() , or do it in "demo" before reading the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM