www.pudn.com > closeonexec.rar > fcntl.cpp


// This program is written by Li,Suke. 
// School of Software and Microelectronics, 
// Beijing University. 
// I hope this program can be useful. 
// September 11, 2006 
 
#include  
#include  
#include  
#include  
 
#include  
#include  
 
const int ARG_LEN = 10; 
 
using namespace std; 
 
int main(int argc, char* argv[]) { 
 
  int fd = 0; 
  int flags = 0; 
 
  int n = 0; 
  pid_t pid = 0; 
 
  const char* hello = "Hello,world\n"; 
 
  if (argc != 2) { 
    cout << "Usage fcntl " << endl; 
    exit(0); 
  } 
 
  fd = open ("test", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC); 
   
  if (fd == -1) { 
    perror("open"); 
    exit(1); 
  } 
 
  n = write(fd,hello,strlen(hello)); 
  if (n == -1) { 
    perror("write"); 
    exit(1); 
  } 
 
 
//  F_GETFD 
//              Read the file descriptor flags. 
//  F_SETFD 
//              Set the file descriptor flags to the value specified by arg. 
 
#ifdef _GETFLAG 
 
  flags = fcntl(fd, F_GETFD); 
  flags = flags & FD_CLOEXEC; 
 
#else 
 
  flags = fcntl(fd, F_GETFD); 
  flags = flags | FD_CLOEXEC; 
  fcntl(fd, F_SETFD, flags); 
 
#endif 
   
  if (flags) { 
 
     cout << "fcntl:Closed after exec() " << endl;   
      
  } else { 
     cout << "fcntl:Not closed after exec()" << endl; 
  } 
 
  pid = fork(); 
 
  if (pid < 0) { 
    perror("fork"); 
    exit(1); 
  } 
 
  if (pid == 0) { 
 
     char argstr[ARG_LEN]; 
     const char *child ="Hello from the child process!"; 
     cout << "Child process:The file descriptor is " << fd << endl; 
     int n = write(fd, child, strlen(child)); 
      
     if (n < 0) { 
       perror("child process's write"); 
       exit(1); 
     } 
     snprintf(argstr, ARG_LEN, "%d",fd); 
     execl(argv[1],argv[1],argstr,0); 
 
  } else {  
    wait(); 
    close(fd); 
  } 
 
}