そのため、argv[] を介して接続するパイプを介して char 配列を前後に送信するパイプを作成しようとしています。現在、db.c で文字 3 と 5 を受信するために、interface.c で配列 (親から子に c_param に送信される param) を受信することに行き詰まっています。3 と 5 が私のパイプがある argv[] のインデックスであることはわかっていますが、それを取得して db.c にメッセージを出力する方法がわかりません。
interface.c は、パイプ、フォークを親プロセスと子プロセスに作成します。char 配列 param は、子プロセスに char 配列 c_param に転送されます。snprintf を使用して、パイプを char に変換し、char 配列 c_param で execl を使用して送信しました。
interface.c:
int main (int argc, char *argv[])
{
int to_Child[2];
int to_Parent[2];
int id, toChildPipe, toParentPipe, err;
char param[100] = "This is the parameter!";
char sendPipe[100];
char recPipe[100];
/*CREATING PIPE*/
toChildPipe = pipe(to_Child);
toParentPipe = pipe(to_Parent);
if(toChildPipe == -1 || toParentPipe == -1)
{
printf ("Error on pipe creation: %d", errno);
exit (1);
}
/*Creating Child Process*/
id = fork();
if(id == 0)
{
/**
*
* IN THE CHILD Process
*
*/
close(to_Child[1]); //reading
close(to_Parent[0]); //writing
char c_param[100];
toChildPipe = read(to_Child[0], c_param, 100);
if (toChildPipe == -1)
{
//If failed
printf("Error on read from pipe from parent: %d\n",errno);
//exit with error
exit(2);
}//Error pipe from parent
snprintf(sendPipe,sizeof(sendPipe), "%d",to_Parent[0]);
snprintf(recPipe,sizeof(recPipe), "%d",to_Child[0]);
err = execl("./db","db",sendPipe,recPipe,(char *)0);
if(err == -1)
{
printf("Error on execl: %d\n", errno);
}//Error execl
toChildPipe = read(to_Child[0], c_param, 100);
if (toChildPipe == -1)
{
//If failed
printf("Error on read from pipe from parent: %d\n",errno);
//exit with error
exit(2);
}//Error pipe from parent
}//CHILD PROCESS
else if (id > 0)
{
/**
*
*IN THE PARENT PROCESS
*
*/
close(to_Child[0]); //writing
close(to_Parent[1]); //reading
toChildPipe = write(to_Child[1],param,100);
if(toChildPipe == -1)
{
printf("Error on write to pipe: %d", errno);
exit(3);
}
/*Piping was successful!*/
exit(0);
}//PARENT PROCESS
else
{
exit(4);
}
}
db.c は interface.c execl から起動し、argv[] を介してパラメーターを受け取り、それを出力する必要があります。db.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
FILE *finput;
int j = 0;
int fd;
int toChildPipe;
char c_param[100];
if(argc > 1)
{
for(j ; j < argc ; j++)
printf("argv = %s\n", argv[j]);
printf("argc = %d\n",argc);
}
fd = atoi(argv[1]);
printf("Statement: %s\n", argv[fd]);
strcpy(c_param, argv[3]);
printf("filename: %s\n", c_param);
}
これは私が得ている現在の出力です。5 と 3 は、メッセージを送信し、現在 db.c で印刷しようとしているメッセージを受信するために必要なインデックスであることを認識しています。
出力 (db.c):
argv = db
argv = 5
argv = 3
argc = 3
Statement: TERM=xterm
十分な情報を提供できたことを願っています。前もって感謝します!