3

execl() 関数を使用してプロセスを呼び出す ac プログラムを作成しています。プロセスの出力と C プログラムの出力を取得します。execl() を使用して呼び出されたプロセスの出力をファイルに保存する必要があります。プログラミングの基礎と、ファイルの入出力も知っています。

これが私のプログラムです:

#include<stdio.h>
#include<unistd.h>
main()
{
printf("\nDisplaying output of ifconfig\n");
execl("/sbin/ifconfig","ifconfig",NULL);
}

出力:

Displaying output of ifconfig

eth1      Link encap:Ethernet  HWaddr 02:00:00:a1:88:21  
      ...........

lo        Link encap:Local Loopback  
      ........

ifconfig の出力をファイルに保存する必要があります。どうすればできますか?

4

2 に答える 2

2

を呼び出す代わりに を使用popenしてプログラムを実行しexecl、 を読み込んでファイルに書き込むことができます。またはsystem、シェルを呼び出す関数を使用して、完全なシェル リダイレクトを含めることができます。

または、 を使用してファイルを開き、openを使用dup2して にリダイレクトしSTDOUT_FILENOます。

実際、そのexecような関数を使用することは非常にまれです。通常、新しいプロセスを作成execし、子プロセスを呼び出します。


openこの場合、 andを使用dup2することをお勧めします。

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

...

/* Open the file for writing (create it if it doesn't exist) */
int fd = open("/path/to/file", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);

/* Make the standard output refer to the newly opened file */
dup2(fd, STDOUT_FILENO);

/* Now we don't need the file descriptor returned by `open`, so close it */
close(fd);

/* Execute the program */
execl("/sbin/ifconfig","ifconfig",NULL);

注:上記のコードには、必要なエラー処理はありません。

于 2013-11-01T18:18:04.470 に答える