파이프를 사용하여 두 프로그램 간에 간단한 문자열을 보내는 방법은 무엇입니까?
인터넷으로 검색해 봤지만 자료가 거의 없어요.작은 예만 들어도 충분합니다.
편집 내 말은, 서로 통신하는 두 개의 다른 C 프로그램 말이야.한 프로그램은 "Hi"를 보내고 다른 프로그램은 "Hi"를 받아야 합니다.그런 거.
일반 파이프는 관련된 두 프로세스만 연결할 수 있습니다.프로세스에 의해 생성되며 마지막 프로세스가 닫히면 사라집니다.
이름붙인 파이프는 동작상 FIFO라고도 불리며 관련 없는2개의 프로세스를 연결하는 데 사용할 수 있으며 프로세스와는 독립적으로 존재합니다.즉, 아무도 사용하지 않아도 파이프는 존재할 수 있습니다.라이브러리 함수를 사용하여 FIFO를 작성합니다.
예
라이터
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
리더.c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
return 0;
}
주의: 간단하게 하기 위해 위의 코드에서는 에러 체크가 생략되었습니다.
C의 파이프 작성에서 파이프를 사용하는 프로그램을 분기하는 방법을 보여 줍니다.fork()를 사용하지 않을 경우 명명된 파이프를 사용할 수 있습니다.
또, 다음과 같은 효과를 얻을 수 있습니다.prog1 | prog2
의 출력을 송신함으로써prog1
책을 읽다stdin
에prog2
. stdin 이라는 이름의 파일을 열어서도 읽을 수 있습니다./dev/stdin
(단, 휴대성은 확실하지 않습니다).
/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
*****************************************************************************
MODULE: pipe.c
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
dup2( STDIN_FILENO, newfd )
그리고 다음을 읽습니다.
char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
perror( "dup2( )" );
exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
printf( "<%s>", reading );
memset( reading, '\0', 1025 );
}
if( r_control < 0 )
perror( "read( )" );
close( fdin );
근데 그런 것 같아요.fcntl
더 나은 해결책이 될 수 있다
echo "salut" | code
한 프로그램이 stdout에 쓴 내용은 stdin을 통해 다른 프로그램이 읽을 수 있습니다.그래서 간단하게 c를 사용해서prog1
인쇄하다printf()
그리고.prog2
(읽기 등을) 읽다scanf()
그럼 그냥 도망쳐요
./prog1 | ./prog2
다음은 샘플입니다.
int main()
{
char buff[1024] = {0};
FILE* cvt;
int status;
/* Launch converter and open a pipe through which the parent will write to it */
cvt = popen("converter", "w");
if (!cvt)
{
printf("couldn't open a pipe; quitting\n");
exit(1)
}
printf("enter Fahrenheit degrees: " );
fgets(buff, sizeof (buff), stdin); /*read user's input */
/* Send expression to converter for evaluation */
fprintf(cvt, "%s\n", buff);
fflush(cvt);
/* Close pipe to converter and wait for it to exit */
status=pclose(cvt);
/* Check the exit status of pclose() */
if (!WIFEXITED(status))
printf("error on closing the pipe\n");
return 0;
}
이 프로그램의 중요한 단계는 다음과 같습니다.
- 그
popen()
부모 프로세스와 파이프 간의 관련성을 확립하는 콜. - 그
fprintf()
파이프를 일반 파일로 사용하여 하위 프로세스의 stdin에 쓰거나 stdout에서 읽는 호출입니다. - 그
pclose()
파이프가 닫히고 하위 프로세스가 종료되는 콜입니다.
이 대답은 미래의 구글러에게 도움이 될 것이다.
#include <stdio.h>
#include <unistd.h>
int main(){
int p, f;
int rw_setup[2];
char message[20];
p = pipe(rw_setup);
if(p < 0){
printf("An error occured. Could not create the pipe.");
_exit(1);
}
f = fork();
if(f > 0){
write(rw_setup[1], "Hi from Parent", 15);
}
else if(f == 0){
read(rw_setup[0],message,15);
printf("%s %d\n", message, r_return);
}
else{
printf("Could not create the child process");
}
return 0;
}
여기서 고급 양방향 파이프 호출 예를 찾을 수 있습니다.
먼저 프로그램1에 스트링을 쓰도록 하겠습니다stdout
(화면에 표시하는 것처럼)그러면 두 번째 프로그램은 다음에서 문자열을 읽어야 합니다.stdin
사용자가 키보드에서 입력하는 것처럼.다음으로 실행한다.
$ program_1 | program_2
언급URL : https://stackoverflow.com/questions/2784500/how-to-send-a-simple-string-between-two-programs-using-pipes
'programing' 카테고리의 다른 글
다른 컴포넌트에서 데이터 접근 (0) | 2022.08.03 |
---|---|
루트 변경 없이 Nuxt.js 미들웨어 재평가 (0) | 2022.08.03 |
Element-UI : 컴포넌트 간 폰트 패밀리 차이 (0) | 2022.08.03 |
vuex의 여러 모듈에 대한 올바른 구문 (0) | 2022.08.03 |
vue-form-generator의 선택 필드를 동적 값으로 채웁니다. (0) | 2022.08.03 |