In these snippets the go program tries to write to C program's stdin. The problem is that the c program starts an infinite loop after the go loop finishes.
main.c
#include <stdio.h>
#include <stdlib.h>
int main(){
int age;
char name[8];
for(;;)
{
scanf(" %s : %d\n",&name, &age);
printf("%s : %d\n",name, age);
}
return 0;
}
run/main.go
func main() {
proc := exec.Command("../main")
stdin, err := proc.StdinPipe()
if err != nil {
fmt.Println(err)
}
defer stdin.Close()
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
fmt.Println("START")
if err = proc.Start(); err != nil {
log.Fatal("An error occured: ", err)
}
for i := 0; i < 500; i++ {
io.WriteString(stdin, fmt.Sprintf("hello : %d\n", i))
//How to wait here and read from printf()?
}
//proc.Process.Kill() Here proc gets killed too fast
fmt.Println("END")
}
When killed, process doesn't complete it's output
Output
START
END
hello : 497
hello : 498
hello : 499
hello : 499
Output Expected
START
....
hello : 497
hello : 498
hello : 499
END
stdoutof the child process to the standard output of your process. If you don't want that, don't do that and read from theproc.Stdout. Or have the child program send a signal when it's done.\nfrom thescanf: stackoverflow.com/questions/15443483/using-n-in-scanf-in-cfor(;;)is an infinite loop since there's nothing in it to break out. Use the return value fromscanfto determine that it failed and break there.