APUEのdup,dup 2関数リダイレクト標準出力例


目的:リダイレクト基準を1つのファイルに出力します.
この2つの関数を定義するヘッダファイルはunistdです.h 
このヘッダファイルは、次の3つの定数を同時に定義します.
* stdIN_FILENO=0標準入力
* stdOUT_FILENO=1標準出力
* stdERR_FILENO=2標準エラー出力
dupとdup 2関数
#include
int dup (int filedes);
int dup2 ( int filedes,int filedes2);
2つの関数の戻り値:成功すると新しいファイル記述子が返され、エラーが発生すると-1が返されます.
dupによって返される新しいファイル記述子は、現在使用可能なファイル記述子の最小値に違いありません.
dup 2を使用すると、filedes 2パラメータで新しい記述子の数値を指定できます.filedes 2が開いている場合は、先に閉じます.filedesがfiledes 2に等しい場合、dup 2はdiledes 2を返し、閉じない.
リダイレクト標準出力
例1:
#include<stdio.h>
#include<unistd.h>
#define TESTSTR "Hello dup2
" int main(int argc,char **argv) { int fd; fd =open("testdup2",0666);// if(fd<0) { printf("open error
"); exit(-1); } if(dup2(fd,STDOUT_FILENO) < 0) // fd { printf("error in dup2
"); } printf("TESTSTR
"); printf(TESTSTR); return 0;// close(fd) } // TESTSTR <span style="white-space:pre"> </span>Hello dup2

例2:makefileの作成
dup2_1.c
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#define TESTSTR "Hello dup2
"
int main(int argc,char **argv)
{
        int fd;
        if(argc<2)
        {
                printf("Usage: [file1] [file2] 
",strerror(errno)); exit(1); } print(argv[1],TESTSTR); return 0; }

print.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

void print(const char *filename,const char *str)
{
        int fd;
        if((fd = open(filename,0666))<0)
{
        printf("open erro");
        exit(1);
}
        dup2(fd, STDOUT_FILENO);

        printf("Say = %s",str);
}

print.h
#ifndef _PRINT_H  
#define _PRINT_H  
  
void print(const char *filename, const char *str);  
  
#endif

makefile
[songyong@centos6 practice]$ cat makefile 
bins=main
objs=dup2_1.o
srcs=dup2_1.c

$(bins):$(objs)
        gcc -o main dup2_1.o print.o

$(objs):$(srcs)
        gcc -c dup2_1.c
        gcc -c print.c print.h 
clean:
        rm -f $(bins) *.o

テスト:
[songyong@centos6 practice]$ ./main
Usage: [file1] [file2] 
[songyong@centos6 practice]$ ./main test_1.c 
[songyong@centos6 practice]$ cat test_1.c 
Say = Hello dup2