ANSWER in this previous question: https://mcmap.net/q/25577/-how-to-make-child-process-die-after-parent-exits It was not checked and quiet down, so I missed it. Already asked to be posted here
I am playing around with an application that creates a socket connection on a child process.
Now my problem is that trying to test it, but every time I run the application Netbeans creates main(Build, Run) and main(Run) when I close by clicking the red square or bottom right main(run) X button. The process "terminate" but it stays there, and then at exiting IDE it says "Exiting the IDE will terminate..." main(run)"
This is my first time with fork (and c) so I suppose I am not terminating the child process when terminating the main process, but shouldn't i be able to terminate manually too? Or is there a way for me to have a socket connection that constantly listens without blocking the rest of the code?
(note connection is not correct, since it still has blocking)
connection()
...
connection() {
int pid = fork();
if (pid < 0)
{
perror("ERROR on fork");
exit(1);
}
if (pid == 0)
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
fd_set fds;
struct timeval timeout;
int rc;
/* Set time limit. */
timeout.tv_sec = 0;
timeout.tv_usec = 10;
char buffer[256];
portno = 4444;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("Localhost");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1) {
/* Create a descriptor set containing our two sockets. */
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
if (rc > 0) {
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
}
rc = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (rc==-1) {
perror("select failed");
}
if (rc > 0) {
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Client: Server send %s",buffer);
useEvent(buffer);
}
}
}
onExit()
) and notify the child via a IPC mechanism of your choice. This might even be possible in both directions, since everyone knows the other ones pid. – Mantelletta