Why printing time does not decrease using processes in this program? - process

I'm making a program in C on CentOS using processes, and am trying to print the numbers from 0 to 1000000 in two different terminals in the shortest time possible. But time increased twice compared to printing on a single terminal. In a single terminal takes 6 or 7 seconds to print, with the two terminals takes 12-13 seconds. Is there any reason why this happens?
main(int argc,char *argv[])
{
pid_t pid;
time_t t1,t2;
time(&t1);
pid=fork();
if(pid==0)
{
int x;
FILE *da1=fopen("/dev/pts/2","w+");
for(x=0;x<=1000000;x++)
fprintf(da1,"%d ",x);
exit(0);
}
else
{
int y;
FILE *da2=fopen("/dev/pts/3","w+");
for(y=0;y<=1000000;y++)
fprintf(da2,"%d ",y);
}
wait(0);
time(&t2);
printf("\nTime %i\n",t2-t1);
}

Related

For the following race condition example, why an inconsistent result comes up only in some environments, but not in some others?

The following code is about the classical producer and consumer problem and there is a race condition here. When I run this example in MinGW in Windows 10, we have a very large probability (e.g., 80%) of having an inconsistent result. However, when I run it in Ubuntu, the probability is extremely low.
Besides, when I run a similar code in Java, the probability of having an inconsistent result is also very high.
So, could anyone explain what is different behind. I think it is because of different scheduling mechanisms and different time slice settings.
#include <stdio.h>
#include <pthread.h>
int count = 0;
void *producer(){
for(int i = 0;i<10000;i++)
count++;
}
void *consumer() {
for(int i = 0;i<10000;i++)
count--;
}
int main(int argc, const char *argv[]){
printf("initial count: %d\n",count);
pthread_t t1, t2;
pthread_create(&t1, NULL, producer,NULL);
pthread_create(&t2, NULL, consumer,NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("final count: %d\n",count);
return 0;
}

Run child processes in parallel with fork

I need to create "n" child processes and they have to sleep a random number of seconds, and the parent process have to advise when any child process has finished. The problem is that each child process runs one after other and I need them to work in parallel. (In the code I'm just creating 3 children.)
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(void)
{
pid_t pid;
int x,zeit,status,w,n=0;
for(x=1;x<=3;x++)
{
pid=fork();
n++;
srand(time(NULL));
if(pid)
{
w=wait(&status);
printf("Process %d finished in %d seconds (Dad:%d cuenta %d)\n",w,WEXITSTATUS(status),getppid(),n);
}
else
{
int n;
zeit=rand()%3+1;
sleep(zeit);
exit(zeit);
}
}
exit(0);
return 0;
}
You're explicitly waiting for each process to finish before you start the next one
for(x=1;x<=3;x++)
{
pid=fork();
n++;
srand(time(NULL));
if(pid)
{
w=wait(&status);
printf("Process %d finished in %d seconds (Dad:%d cuenta %d)\n",
w, WEXITSTATUS(status), getppid(), n);
...
}
If you want them to run in parallel, you're going to have to make 3 different processes, and start them off before you wait for any one of them to finish.

Scanf in Objective C Crashes Xcode And the Program

I have removed scanf from the code and the rest of the program runs with no issue. When the code reaches scanf, and after I type a number, xcode 'loses connection' and displays the error "Program ended with exit code: -1". I have also tried making 'input' an int, changed the name of variable input in case there was a conflict there, and tried it without fflush in the code. I am running Mountain Lion on Oracle VM Virtualbox, and my computer is on Windows 7, if that's relevant.
What am I doing wrong?
#import Foundation/Foundation.h
#include stdio.h
int main(int argc, const char * argv[])
{
#autoreleasepool {
float input = 1;
int i = 0;
float total = 0;
int max = 0;
int min = 1000;
while (input != 0){
NSLog(#"Please put in a number. \n");
scanf("%f", &input);
fflush(stdin);
if(input > max){
max = input;
}
if(input < min){
min = input;
}
total = total + input;
i++;
}
printf("The number of entered numbers was %i \n", i);
printf("The sum of the entered numbers is %f\n", total);
total = total/i;
printf("The average of all the numbers is %f\n", total);
printf("The highest number entered is %i\n", max);
printf("The lowest number entered is %i\n", min);
}
return 0;
}
fflush(stdin);
You probably want
fflush(stdout)
I'm not sure what fflush() will do with an FILE* opened for input.
This may or may not be the cause of your issues.
Return and Enter key have a different meaning inside Xcode. You go to the product menu and select build build for running and execute it in the terminal it will work fine.
Inside Xcode the Enter key in the numpad stops the program with a -1 return code. I am not sure whether this is bug or a feature, but I could not find the key in the keybinding for Xcode.
Please check here

Objective c, Scanf() string taking in the same value twice

Hi all I am having a strange issue, when i use scanf to input data it repeats strings and saves them as one i am not sure why.
Please Help
/* Assment Label loop - Loops through the assment labels and inputs the percentage and the name for it. */
i = 0;
j = 0;
while (i < totalGradedItems)
{
scanf("%s%d", assLabel[i], &assPercent[i]);
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%s", assLabel[i]);
i++;
}
Input Data
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
Output Via Console
Prog1QuizQuizProg2MdtmMdtmFinal
Final diagnosis
You don't show your declarations...but you must be allocating just 5 characters for the strings:
When I adjust the enum MAX_ASSESSMENTLEN from 10 to 5 (see the code below) I get the output:
Prog1Quiz 20
Quiz 20
Prog2Mdtm 20
Mdtm 15
Final 25
You did not allow for the terminal null. And you didn't show us what was causing the bug! And the fact that you omitted newlines from the printout obscured the problem.
What's happening is that 'Prog1' is occupying all 5 bytes of the string you read in, and is writing a null at the 6th byte; then Quiz is being read in, starting at the sixth byte.
When printf() goes to read the string for 'Prog1', it stops at the first null, which is the one after the 'z' of 'Quiz', producing the output shown. Repeat for 'Prog2' and 'Mtdm'. If there was an entry after 'Final', it too would suffer. You are lucky that there are enough zero bytes around to prevent any monstrous overruns.
This is a basic buffer overflow (indeed, since the array is on the stack, it is a basic Stack Overflow); you are trying to squeeze 6 characters (Prog1 plus '\0') into a 5 byte space, and it simply does not work well.
Preliminary diagnosis
First, print newlines after your data.
Second, check that scanf() is not returning errors - it probably isn't, but neither you nor we can tell for sure.
Third, are you sure that the data file contains what you say? Plausibly, it contains a pair of 'Quiz' and a pair of 'Mtdm' lines.
Your variable j is unused, incidentally.
You would probably be better off having the input loop run until you are either out of space in the receiving arrays or you get a read failure. However, the code worked for me when dressed up slightly:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char assLabel[10][10];
int assPercent[10];
int i = 0;
int totalGradedItems = 5;
while (i < totalGradedItems)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
{
fprintf(stderr, "Error reading\n");
exit(1);
}
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
i++;
}
return 0;
}
For the quoted input data, the output results are:
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
I prefer this version, though:
#include <stdio.h>
enum { MAX_GRADES = 10 };
enum { MAX_ASSESSMENTLEN = 10 };
int main(void)
{
char assLabel[MAX_GRADES][MAX_ASSESSMENTLEN];
int assPercent[MAX_GRADES];
int i = 0;
int totalGradedItems;
for (i = 0; i < MAX_GRADES; i++)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
break;
}
totalGradedItems = i;
for (i = 0; i < totalGradedItems; i++)
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
return 0;
}
Of course, if I'd set up the scanf() format string 'properly' (meaning safely) so as to limit the length of the assessment names to fit into the space allocated, then the loop would stop reading on the second attempt:
...
char format[10];
...
snprintf(format, sizeof(format), "%%%ds%%d", MAX_ASSESSMENTLEN-1);
...
if (scanf(format, assLabel[i], &assPercent[i]) != 2)
With MAX_ASSESSMENTLEN at 5, the snprintf() generates the format string "%4s%d". The code compiled reads:
Prog 1
and stops. The '1' comes from the 5th character of 'Prog1'; the next assessment name is '20', and then the conversion of 'Quiz' into a number fails, causing the input loop to stop (because only one of two expected items was converted).
Despite the nuisance value, if you want to make your scanf() strings adjust to the size of the data variables it is reading into, you have to do something akin to what I did here - format the string using the correct size values.
i guess, you need to put a
scanf("%s%d", assLabel[i], &assPercent[i]);
space between %s and %d here.
And it is not saving as one. You need to put newline or atlease a space after %s on print to see difference.
add:
when i tried
#include <stdio.h>
int main (int argc, const char * argv[])
{
char a[1][2];
for(int i =0;i<3;i++)
scanf("%s",a[i]);
for(int i =0;i<3;i++)
printf("%s",a[i]);
return 0;
}
with inputs
123456
qwerty
sdfgh
output is:
12qwsdfghqwsdfghsdfgh
that proves that, the size of string array need to be bigger then decleared there.

Out of memory error. Allocating...

I'm trying to use a gprof command: gprof -s executable.exe gmon.out gmon.sum to merge profiling data gathered from 2 runs of my programs. But the following error appears:
gprof: out of memory allocating 3403207348 bytes after a total of 196608 bytes
My program is quite simple (just one for loop). If i run it once, the run time is too short (it shows 0.00s) for gprof to record.
In CygWin, I do the following steps:
gcc -pg -o fl forAndWhilLoop.c
fl (run the program)
mv gmon.out gmon.sum
fl (run the program)
gprof -s fl.exe gmon.out gmon.sum
gprof fl.exe gmon.sum>gmon.out
gprof fl.exe
My program:
int main(void)
{
int fac=1;
int count=10;
int k;
for(k=1;k<=count;k++)
{
fac = fac * k;
}
return 0;
}
So can anyone help me with this problem? Thanks!
If all you want is to time it, on my machine it's 105ns. Here's the code:
void forloop(void){
int fac=1;
int count=10;
int k;
for(k=1;k<=count;k++)
{
fac = fac * k;
}
}
int main(int argc, char* argv[])
{
int i;
for (i = 0; i < 1000000000; i++){
forloop();
}
return 0;
}
Get the idea? I used a hand-held stopwatch. Since it runs 10^9 times, seconds = nanoseconds.
Unrolling the inner loop like this reduced the time to 92ns;
int k = 1;
while(k+5 <= count){
fac *= k * (k+1) * (k+2) * (k+3) * (k+4);
k += 5;
}
while(k <= count){
fac *= k++;
}
Switching to Release build from Debug brought it down to 21ns. You can only expect that kind of speedup in an actual hotspot, which this is.
It seems that pprof instead of gprof should be executed