我試圖運行一個程序,它採取以下行動:發送字符從一個程序到另一個通過管道一點兒也不工作
- 叉一個子進程,將推出另一編譯的C程序 - draw.out
- 父進程然後從鍵盤
- 輸入用於用戶等待輸入隨後經由管
- draw.out從管道中讀取傳遞給draw.out程序,並使用該輸入
這裏有兩個程序,draw.out
工作正常(俄羅斯方塊遊戲),但沒有從管道輸入,我的錯誤是什麼?
文件1:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
#include <curses.h>
#include <string.h>
int main(void)
{
int fd[2], childpid;
//pid_t childpid;
char input = 'o';
char readbuffer[80];
pipe(fd);
if ((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if (childpid == 0)
{
close(0);
dup(fd[0]);
execl("draw.out", NULL);
}
else
{
close(fd[0]);
while (input != 'q')
{
input = getch();
if (input == 'a' || input == 's' || input == 'd' || input == 'w' || input == 'q')
{
write(fd[1], &input, 1);
kill(getpid() + 1, SIGUSR2);
}
}
exit(0);
}
return 1;
}
文件2:
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void print_screen(int a, int b, int c, int t, int flat);
void my_handler(int signum);
int a = 9, b = 10, c = 11, t = 0, flat = 1;
int newfd = 0;
int main(void)
{
if (signal(SIGUSR2, my_handler) == SIG_ERR)
{
printf("Pærent: Unable to create handler for SIGUSR2\n");
}
while (t < 20)
{
system("clear");
print_screen(a, b, c, t, flat);
sleep(1);
t++;
}
}
void my_handler(int signum)
{
if (signum == SIGUSR2)
{
printf("signal arrived");
char input;
fgets(&input, sizeof(input), stdin);
switch (input)
{
case 'a':
if (a > 1)
{
a--;
b--;
c--;
}
break;
case 's':
t++;
break;
case 'd':
if (c < 18)
{
a--;
b--;
c--;
}
case 'w':
if (flat == 1)
{
flat = 0;
}
else
{
if (b<18 && b>1)
{
flat = 1;
}
}
break;
case 'q':
exit(0);
}
}
}
void print_screen(int a, int b, int c, int t, int flat)
{
char str[420] = "\n";
int i, j;
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (i != 19 && !(j>0 && j < 19))
{
strcat(str, "*");
}
else if (i == 19)
{
strcat(str, "*");
}
else
{
if (flat == 1 && i == t && (j == a || j == b || j == c))
{
strcat(str, "-");
}
else if (flat == 0 && j == b && (i == t || i == t - 1 || i == t + 1))
{
strcat(str, "-");
}
else
{
strcat(str, " ");
}
}
}
strcat(str, "\n");
}
puts(str);
}
這是什麼'殺號(getpid()+ 1,SIGUSR2);'?這裏假設 –
'dup(fd [0]);''可能需要'dup2' - http://linux.die.net/man/2/dup2 –
'fgets(&input,sizeof(input),stdin); 「這將處理不是爲了角色。也許'讀'來鏡像'寫'? –