请输入您要查询的百科知识:

 

词条 Dup (system call)
释义

  1. C library POSIX definition

  2. dup2 for input/output redirection

  3. See also

  4. References

{{lowercase}}{{refimprove|date=March 2012}}

In Unix-like operating systems, dup (short for "duplicate") and dup2 system calls create a copy of a given file descriptor. This new descriptor actually does not behave like a copy, but like an alias of the old one.

C library POSIX definition

The dup and dup2 calls are standardized by the POSIX specification.[1]

int dup (int oldfd);

int dup2 (int oldfd, int newfd);

The former allocates the first available descriptor, just like open() behaves; an alternative way to duplicate a file descriptor to an unspecified place is the fcntl system call with F_DUPFD command.

The latter places the copy into newfd. If newfd is open, it is closed first.

dup2 for input/output redirection

{{expand section|date=March 2012}}

Unix shells use dup2 for input/output redirection. Along with pipe(), it is a tool on which Unix pipes rely.

The following example uses pipe() and dup() in order to connect two separate processes (program1 and program2) using Unix pipes:

  1. include
  2. include
  3. include

/* function prototypes */

void die(const char*);

int main(int argc, char **argv) {

int pdes[2];

pid_t child;

if(pipe(pdes) == -1)

die("pipe()");

child = fork();

if(child == (pid_t)(-1))

        	die("fork()"); /* fork failed */ 

if(child == (pid_t)0) {

        	close(1);       /* close stdout */        	        	if(dup(pdes[1]) == -1)        		die("dup()");        	        	/* now stdout and pdes[1] are equivalent (dup returns lowest free descriptor) */
        	if((execlp("program1", "program1", "arg1", NULL)) == -1)        		die("execlp()");

_exit(EXIT_SUCCESS);

} else {

        	close(0);       /* close stdin */        	        	if(dup(pdes[0]) == -1)        		die("dup()");
        	if((execlp("program2", "program2", "arg1", NULL)) == -1)        		die("execlp()");

exit(EXIT_SUCCESS);

}

return 0;

}

void die(const char *msg) {

perror(msg);

exit(EXIT_FAILURE);

}

See also

  • File descriptor – how it works and other functions related to open

References

1. ^{{cite web|title=dup, dup2|url=http://pubs.opengroup.org/onlinepubs/9699919799/functions/dup.html|website=opengroup.org}}
  • Advanced Programming in the UNIX Environment by W. Richard Stevens {{ISBN|81-7808-096-6}}

2 : C POSIX library|System calls

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/11/11 18:56:45