while loop with fork not working

Hi, could someone suggest how I can correct the code so the command line continues to ask for a user number, until the user enters 'q', which cancels the program.

I am using a fork and when pressing 'q', the output is wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>
#include <string.h>    /* Needed for the strcat function. */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h>  /* Needed for the wait function. */
#include <unistd.h>    /* needed for the fork function. */

#define SHMSIZE 25
int main() 
{
	char *shm;
	int n;  /* Variable to get the user's number into the program. */
	int shmid;
	while (n != 'q') // Request user for input numbers until the use presses 'q' to quit (the entire program I guess?).
	{
		if(fork() == 0)  // Parent of fork.
		{
			shmid = shmget(2009, SHMSIZE, 0);
			shm = shmat(shmid, 0, 0);
			char *s = (char *) shm;
			*s = '\0';  /* Set first location to string terminator, for appending later. */
			{
				
				printf("Please enter a number, E.g., 10: ");
				scanf("%d", &n);
				sprintf(s, "%s%d", s, n);  /* Append number to string. */
				strcat(s, "\n");  /* Append newline. */
				printf ("\nParent wrote %s\n", shm);
				shmdt(shm);
			}		
		}
		else // Child of fork.
		{
			/* Variable s removed, as wasn't used. */
			/* Removed first call to wait, as it held up parent process. */
			shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
			shm = shmat(shmid, 0, 0);
			wait(NULL);
			printf ("Child read %s\n", shm);
			shmdt(shm);
			shmctl(shmid, IPC_RMID, NULL);
		}
	}
	return 0;
}
while(1)
{
//pthread_mutex_lock(&mVar);
i=globalI;
printf ("%s:%d\n",(char *)s,i);
FILE *f = fopen("file.txt", "a");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}

fprintf(f, "Some text: %s:%d\n",(char *) s,i);
i=i+1;
globalI=i;
fclose(f);
//pthread_mutex_unlock(&mVar);
}

Read the above code. You will get some idea. Essentially your code is doing the bulk of the work but what is missing is reading and then evaluating if what is entered is q or not. My code takes care of that. Another example I have provided.

while(1)
{
gets(string);

if(strcmp(string,"exit()")==0)
break;
char * newPointer=returnPointerToMemLocation(string);
puts(newPointer);

}
Last edited on
Topic archived. No new replies allowed.