在阅读dup3系统调用时,我知道它将仅更改重复文件描述符的O_CLOEXEC标志。但是,当我在下面的程序中为所有3个输出编写程序时,打印的标志是否存在,并且该标志基于打开时是否在原始文件描述符中指定了O_CLOEXEC。怎么了 ?我真的不明白
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
void PrintUsage();
void PrintVersion();
void PrintStatusCloexec( int );
void dup3_code( const char * );
void main(int argc, char *argv[])
{
int hflag = FALSE, vflag = FALSE, nflag = FALSE, src_flag = FALSE;
char *src_file_name = NULL;
int src_len = 0;
char c;
int option_index;
struct option long_options[] = {
{ "version", no_argument, 0, 0},
{ "help", no_argument, 0, 0},
{ "src_file", required_argument, 0, 0},
{0,0,0,0}
};
while( ( c = getopt_long(argc, argv, "hvs:", long_options, &option_index) ) != -1 )
{
switch( c )
{
case 'h':
hflag = TRUE;
break;
case 'v':
vflag = TRUE;
break;
case 's':
src_flag = TRUE;
src_len = strlen( optarg );
src_file_name = (char *)calloc(1, src_len + 1);
strncpy(src_file_name, optarg, src_len);
break;
case 0:
switch(option_index)
{
case 0: vflag = TRUE;
break;
case 1: hflag = TRUE;
break;
case 2: src_flag = TRUE;
src_file_name = (char *) calloc(1, strlen(optarg) + 1);
strncpy(src_file_name, optarg, src_len);
break;
default: printf(" Invalid argument index : %d", option_index );
exit(EXIT_FAILURE);
}
break;
case '?':
break;
default:
printf( " Invalid option %c", c);
exit(EXIT_FAILURE);
}
}
if( vflag == FALSE && src_flag == FALSE )
{
PrintUsage();
}
if(hflag == TRUE)
{
PrintUsage();
}
if(vflag == TRUE )
{
PrintVersion();
}
if(src_flag == TRUE)
{
printf(" src file name : %s\n", src_file_name);
dup3_code( src_file_name );
}
exit(EXIT_SUCCESS);
}
void PrintUsage()
{
printf(" Usage : %s [-h] [-v] [-s|src_file file_name]\n" , __FILE__ );
}
void PrintVersion()
{
printf(" Version : 1.0\n");
}
void dup3_code( const char *file_name )
{
int fd = open( file_name, O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if( fd == -1 )
{
printf(" Error opening file %s : %s\n", file_name, strerror(errno));
exit(EXIT_FAILURE);
}
printf( "After file is opened:\n");
PrintStatusCloexec( fd );
int new_fd = dup( fd );
printf( "After dup:\n" );
PrintStatusCloexec( new_fd );
close( new_fd );
new_fd = dup3( fd, new_fd, O_CLOEXEC );
printf( "After dup3:\n" );
PrintStatusCloexec( new_fd );
close( new_fd );
close( fd );
}
void PrintStatusCloexec( int fd )
{
int flags = fcntl( fd, F_GETFL );
if( flags & O_CLOEXEC )
{
printf( " close on exec flag for file id %d is set\n", fd );
}
else
{
printf( " close on exec flag for file id %d is not set\n", fd );
}
}
也是我的GNU C库版本:
GNU C Library (Ubuntu EGLIBC 2.15-0ubuntu10) stable release version 2.15.
最佳答案
要获取标志的当前状态,您需要使用F_GETFD
并查看FD_CLOEXEC
位。 F_GETFL
仅返回属于打开文件描述的标志(即,在重复的描述符和分支的进程之间共享的标志)。 O_CLOEXEC
结果中是否存在F_GETFL
没有意义。
关于c - dup3的工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25426541/