Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 11/74 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Problem in using a second call to send() in C

    - by Paulo Victor
    Hello. Right now I'm working in a simple Server that receives from client a code referring to a certain operation. The server receives this data and send back the signal that it's waiting for the proper data. /*Server Side*/ if (codigoOperacao == 0) { printf("A escolha foi 0\n"); int bytesSent = SOCKET_ERROR; char sendBuff[1080] = "0"; /*Here "send" returns an error msgm while trying to send back the signal*/ bytesSent = send(socketEscuta, sendBuff, 1080, 0); if (bytesSent == SOCKET_ERROR) { printf("Erro ao enviar"); return 0; } else { printf("Bytes enviados : %d\n", bytesSent); char structDesmontada[1080] = ""; bytesRecv = recebeMensagem(socketEscuta, structDesmontada); printf("structDesmontada : %s", structDesmontada); } } Following here is the client code responsible for sending the operation code and receiving the signal char sendMsg[1080] = "0"; char recvMsg[1080] = ""; bytesSent = send(socketCliente, sendMsg, sizeof(sendMsg), 0); printf("Enviei o codigo (%d)\n", bytesSent); /*Here the program blocks in a infinite loop since the server never send anything*/ while (bytesRecv == SOCKET_ERROR) { bytesRecv = recv(socketCliente, recvMsg, 1080, 0); if (bytesRecv > 0) { printf("Recebeu\n"); } Why this is happening only in the second attempt to send some data? Because the first call to send() works fine. Hope someone can help!! Thnks

    Read the article

  • Prime Numbers in C?

    - by Ali Azam Rana
    FIRST PROGRAM #include<stdio.h> void main() { int n,c; printf("enter a numb"); scanf("%i",n); for(c=2;c<=n;c++) { if(n%c==0) break; } if(c==n) printf("\nprime\n"); else printf("\nnot prime\n"); getchar(); } SECOND PROGRAM #include <stdio.h> int main() { printf("Enter a Number\n"); int in,loop,rem,chk; scanf("%d",&in); for (loop = 1; loop <=in; loop++) { rem = in % loop; if(rem == 0) chk = chk +1; } if (chk == 2) printf("\nPRIME NUM ENTERED\n"); else printf("\nNUM ENTERED NOT PRIME\n"); getchar(); } the 2nd program works other was the one my friend wrote the program looks fine but on checking it by stepping into we found that the if condition in first program is coming true under every input so whats the logical error here please help me found out......

    Read the article

  • mysterical error

    - by Görkem Buzcu
    i get "customer_service_simulator.exe stopped" error, but i dont know why? this is my c programming project and i have limited time left before deadline. the code is: #include <stdio.h> #include <stdlib.h> #include<time.h> #define FALSE 0 #define TRUE 1 /*A Node declaration to store a value, pointer to the next node and a priority value*/ struct Node { int priority; //arrival time int val; //type int wait_time; int departure_time; struct Node *next; }; Queue Record that will store the following: size: total number of elements stored in the list front: it shows the front node of the queue (front of the queue) rear: it shows the rare node of the queue (rear of the queue) availability: availabity of the teller struct QueueRecord { struct Node *front; struct Node *rear; int size; int availability; }; typedef struct Node *niyazi; typedef struct QueueRecord *Queue; Queue CreateQueue(int); void MakeEmptyQueue(Queue); void enqueue(Queue, int, int); int QueueSize(Queue); int FrontOfQueue(Queue); int RearOfQueue(Queue); niyazi dequeue(Queue); int IsFullQueue(Queue); int IsEmptyQueue(Queue); void DisplayQueue(Queue); void sorteddequeue(Queue); void sortedenqueue(Queue, int, int); void tellerzfunctionz(Queue *, Queue, int, int); int main() { int system_clock=0; Queue waitqueue; int exit, val, priority, customers, tellers, avg_serv_time, sim_time,counter; char command; waitqueue = CreateQueue(0); srand(time(NULL)); fflush(stdin); printf("Enter number of customers, number of tellers, average service time, simulation time\n:"); scanf("%d%c %d%c %d%c %d",&customers, &command,&tellers,&command,&avg_serv_time,&command,&sim_time); fflush(stdin); Queue tellerarray[tellers]; for(counter=0;counter<tellers;counter++){ tellerarray[counter]=CreateQueue(0); //burada teller sayisi kadar queue yaratiyorum } for(counter=0;counter<customers;counter++){ priority=1+(int)rand()%sim_time; //this will generate the arrival time sortedenqueue(waitqueue,1,priority); //here i put the customers in the waiting queue } tellerzfunctionz(tellerarray,waitqueue,tellers,customers); DisplayQueue(waitqueue); DisplayQueue(tellerarray[0]); DisplayQueue(tellerarray[1]); // waitqueue-> printf("\n\n"); system("PAUSE"); return 0; } /*This function initialises the queue*/ Queue CreateQueue(int maxElements) { Queue q; q = (struct QueueRecord *) malloc(sizeof(struct QueueRecord)); if (q == NULL) printf("Out of memory space\n"); else MakeEmptyQueue(q); return q; } /*This function sets the queue size to 0, and creates a dummy element and sets the front and rear point to this dummy element*/ void MakeEmptyQueue(Queue q) { q->size = 0; q->availability=0; q->front = (struct Node *) malloc(sizeof(struct Node)); if (q->front == NULL) printf("Out of memory space\n"); else{ q->front->next = NULL; q->rear = q->front; } } /*Shows if the queue is empty*/ int IsEmptyQueue(Queue q) { return (q->size == 0); } /*Returns the queue size*/ int QueueSize(Queue q) { return (q->size); } /*Shows the queue is full or not*/ int IsFullQueue(Queue q) { return FALSE; } /*Returns the value stored in the front of the queue*/ int FrontOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->front->next->val; else { printf("The queue is empty\n"); return -1; } } /*Returns the value stored in the rear of the queue*/ int RearOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->rear->val; else { printf("The queue is empty\n"); return -1; } } /*Displays the content of the queue*/ void DisplayQueue(Queue q) { struct Node *pos; pos=q->front->next; printf("Queue content:\n"); printf("-->Priority Value\n"); while (pos != NULL) { printf("--> %d\t %d\n", pos->priority, pos->val); pos = pos->next; } } void enqueue(Queue q, int element, int priority){ if(IsFullQueue(q)){ printf("Error queue is full"); } else{ q->rear->next=(struct Node *)malloc(sizeof(struct Node)); q->rear=q->rear->next; q->rear->next=NULL; q->rear->val=element; q->rear->priority=priority; q->size++; } } void sortedenqueue(Queue q, int val, int priority) { struct Node *insert,*temp; insert=(struct Node *)malloc(sizeof(struct Node)); insert->val=val; insert->priority=priority; temp=q->front; if(q->size==0){ enqueue(q, val, priority); } else{ while(temp->next!=NULL && temp->next->priority<insert->priority){ temp=temp->next; } //printf("%d",temp->priority); insert->next=temp->next; temp->next=insert; q->size++; if(insert->next==NULL){ q->rear=insert; } } } niyazi dequeue(Queue q) { niyazi del; niyazi deli; del=(niyazi)malloc(sizeof(struct Node)); deli=(niyazi)malloc(sizeof(struct Node)); if(IsEmptyQueue(q)){ printf("Queue is empty!"); return NULL; } else { del=q->front->next; q->front->next=del->next; deli->val=del->val; deli->priority=del->priority; free(del); q->size--; return deli; } } void sorteddequeue(Queue q) { struct Node *temp; struct Node *min; temp=q->front->next; min=q->front; int i; for(i=1;i<q->size;i++) { if(temp->next->priority<min->next->priority) { min=temp; } temp=temp->next; } temp=min->next; min->next=min->next->next; free(temp); if(min->next==NULL){ q->rear=min; } q->size--; } void tellerzfunctionz(Queue *a, Queue b, int c, int d){ int i; int value=0; int priority; niyazi temp; temp=(niyazi)malloc(sizeof(struct Node)); if(c==1){ for(i=0;i<d;i++){ temp=dequeue(b); sortedenqueue((*(a)),temp->val,temp->priority); } } else{ for(i=0;i<d;i++){ while(b->front->next->val==1){ if((*(a+value))->availability==1){ temp=dequeue(b); sortedenqueue((*(a+value)),temp->val,temp->priority); (*(a+value))->rear->val=2; } else{ value++; } } } } } //end of the program

    Read the article

  • C programming - How to print numbers with a decimal component using only loops?

    - by californiagrown
    I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third. I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component. Here is what I have for the while loop conversions: #include <stdio.h> #define KM_TO_MILE .62 main (void) { double km, mi, count; printf ("This program converts kilometers to miles.\n"); do { printf ("\nEnter a positive non-zero number"); printf (" of kilometers of the race: "); scanf ("%lf", &km); getchar(); }while (km <= 1); printf ("\n KILOMETERS MILES (while loop)\n"); printf (" ========== =====\n"); count = 1; while (count <= km) { mi = KM_TO_MILE * count; printf ("%8.3lf %14.3lf\n", count, mi); ++count; } getchar(); } The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.). Can someone point me in the right direction on this? I'd really appreciate any help! :)

    Read the article

  • char array split ip with strtok

    - by user1480139
    I'm trying to split a IP address like 127.0.0.1 from a file: using following C code: pch2 = strtok (ip,"."); printf("\npart 1 ip: %s",pch2); pch2 = strtok (NULL,"."); printf("\npart 2 ip: %s",pch2); And IP is a char ip[500], that containt an ip. When printing it prints 127 as part 1 but as part 2 it prints NULL? Can someone help me? EDIT: Whole function: FILE *file = fopen ("host.txt", "r"); char * pch; char * pch2; char ip[BUFFSIZE]; IPPart result; if (file != NULL) { char line [BUFFSIZE]; while(fgets(line,sizeof line,file) != NULL) { if(line[0] != '#') { //fputs(line,stdout); pch = strtok (line," "); printf ("%s\n",pch); strncpy(ip, pch, sizeof(pch)-1); ip[sizeof(pch)-1] = '\0'; //pch = strtok (line, " "); pch = strtok (NULL," "); printf("%s",pch); pch2 = strtok (ip,"."); printf("\nDeel 1 ip: %s",pch2); pch2 = strtok (NULL,"."); printf("\nDeel 2 ip: %s",pch2); //if(strcmp(pch,url) == 0) //{ // result.part1 = //} } } fclose(file); }

    Read the article

  • Why does C++ behave this way?

    - by eSKay
    #include<stdio.h> int b = 0; class A { public: int a;}; class B: public A { int c; int d; public: B(){ b++; a = b; printf("B:%d\n",b); } }; int main() { A* a = new B[10]; B* b = new B[10]; printf("\n%d", a->a); a++; printf("\n%d", a->a); // prints junk value printf("\n\n%d", b->a); b++; printf("\n%d", b->a); return 0; } The second printf prints a junk value. It should figure that it is pointing to an object of type B and increment by the sizof(B). Why does that not happen?

    Read the article

  • Know the row with max characters (C)

    - by l_core
    I have wrote a program in C, to find the row with the max number of characters. Here is the code #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main (int argc, char *argv[]) { char c; /* used to store the character with getc */ int c_tot = 0, c_rig = 0, c_max = 0; /* counters of characters*/ int r_tot = 0; /* counters of rows */ FILE *fptr; fptr = fopen(argv[1], "r"); if (fptr == NULL || argc != 2) { printf ("Error opening the file %s\n'", argv[1]); exit(EXIT_FAILURE); } while ( (c = getc(fptr)) != EOF) { if (c != ' ' && c != '\n') { c_tot++; c_rig++; } if (c == '\n') { r_tot++; if (c_rig > c_max) c_max = c_rig; c_rig = 0; } } printf ("Total rows: %d\n", r_tot); printf ("Total characters: %d\n", c_tot); printf ("Total characters in a row: %d\n", c_max); printf ("Average number of characters on a row: %d\n", (c_tot/r_tot)); printf ("The row with max characters is: %s\n", ??????) return 0; } I can easily find the row with the highest number of characters but how can i print that out? Thank You Folks

    Read the article

  • Function pointers usage

    - by chaitanyavarma
    Hi All, Why these two codes give the same output, Case 1: #include <stdio.h> typedef void (*mycall) (int a ,int b); void addme(int a,int b); void mulme(int a,int b); void subme(int a,int b); main() { mycall x[10]; x[0] = &addme; x[1] = &subme; x[2] = &mulme; (x[0])(5,2); (x[1])(5,2); (x[2])(5,2); } void addme(int a, int b) { printf("the value is %d\n",(a+b)); } void mulme(int a, int b) { printf("the value is %d\n",(a*b)); } void subme(int a, int b) { printf("the value is %d\n",(a-b)); } Output: the value is 7 the value is 3 the value is 10 Case 2 : #include <stdio.h> typedef void (*mycall) (int a ,int b); void addme(int a,int b); void mulme(int a,int b); void subme(int a,int b); main() { mycall x[10]; x[0] = &addme; x[1] = &subme; x[2] = &mulme; (*x[0])(5,2); (*x[1])(5,2); (*x[2])(5,2); } void addme(int a, int b) { printf("the value is %d\n",(a+b)); } void mulme(int a, int b) { printf("the value is %d\n",(a*b)); } void subme(int a, int b) { printf("the value is %d\n",(a-b)); } Output: the value is 7 the value is 3 the value is 10

    Read the article

  • Function pointers uasage

    - by chaitanyavarma
    Hi All, Why these two codes give the same output, Case - 1: #include <stdio.h> typedef void (*mycall) (int a ,int b); void addme(int a,int b); void mulme(int a,int b); void subme(int a,int b); main() { mycall x[10]; x[0] = &addme; x[1] = &subme; x[2] = &mulme; (x[0])(5,2); (x[1])(5,2); (x[2])(5,2); } void addme(int a, int b) { printf("the value is %d\n",(a+b)); } void mulme(int a, int b) { printf("the value is %d\n",(a*b)); } void subme(int a, int b) { printf("the value is %d\n",(a-b)); } Output: the value is 7 the value is 3 the value is 10 Case -2 : #include <stdio.h> typedef void (*mycall) (int a ,int b); void addme(int a,int b); void mulme(int a,int b); void subme(int a,int b); main() { mycall x[10]; x[0] = &addme; x[1] = &subme; x[2] = &mulme; (*x[0])(5,2); (*x[1])(5,2); (*x[2])(5,2); } void addme(int a, int b) { printf("the value is %d\n",(a+b)); } void mulme(int a, int b) { printf("the value is %d\n",(a*b)); } void subme(int a, int b) { printf("the value is %d\n",(a-b)); } Output: the value is 7 the value is 3 the value is 10

    Read the article

  • Sending Images over Sockets in C

    - by Takkun
    I'm trying to send an image file through a TCP socket in C, but the image isn't being reassembled correctly on the server side. I was wondering if anyone can point out the mistake? I know that the server is receiving the correct file size and it constructs a file of that size, but it isn't an image file. Client //Get Picture Size printf("Getting Picture Size\n"); FILE *picture; picture = fopen(argv[1], "r"); int size; fseek(picture, 0, SEEK_END); size = ftell(picture); //Send Picture Size printf("Sending Picture Size\n"); write(sock, &size, sizeof(size)); //Send Picture as Byte Array printf("Sending Picture as Byte Array\n"); char send_buffer[size]; while(!feof(picture)) { fread(send_buffer, 1, sizeof(send_buffer), picture); write(sock, send_buffer, sizeof(send_buffer)); bzero(send_buffer, sizeof(send_buffer)); } Server //Read Picture Size printf("Reading Picture Size\n"); int size; read(new_sock, &size, sizeof(1)); //Read Picture Byte Array printf("Reading Picture Byte Array\n"); char p_array[size]; read(new_sock, p_array, size); //Convert it Back into Picture printf("Converting Byte Array to Picture\n"); FILE *image; image = fopen("c1.png", "w"); fwrite(p_array, 1, sizeof(p_array), image); fclose(image);

    Read the article

  • linux find the command invoked

    - by Subbu
    I am writing a C program which determines the number of bytes read from the standard input . I found out there are ways to give input to the program piped input redirection entering into command line while the program is waiting for input How to find the exact command by which the program was executed from the shell . I tried using command-line arguments but failed . #include <stdio.h> int main(int argc,char *argv[]) { char buffer[100]; int n; for(n=1;n<argc;n++) printf("argument: %s\t",argv[n]); printf("\n"); if(argc==1) printf("waiting for input :"); else if (argc==3) printf("Not waiting for input . Got the source from command itself ."); n = read(0,buffer,100); if(n==-1) printf("\nError occured in reading"); printf("\nReading successfully done\n"); return 0; } Also ,

    Read the article

  • Write a program using 3 threads, one prints 10 'A's and the second prints 'B's and the third prints 10 'C's with synchrornization

    - by user132967
    Iam try to implement this questions using threads and mutex this is my code : include include include include include define Num_thread 3 pthread_mutex_t lett[Num_thread]; void Sleep_rand(double max) { struct timespec delai; delai.tv_sec=max; delai.tv_nsec=0; nanosleep(&delai,NULL); } void *Print_Sequence(); int main() { int i; pthread_t tid[Num_thread];// this is threads identifier for(i=0;i<Num_thread;i++) pthread_mutex_init(&lett[i],0); for(i=0;i<Num_thread;i++) { printf("i=%d\n",i); /* create the threads / pthread_create(&tid[i], / This variable will have the thread is after successful creation / NULL, / send the thread attributes / Print_Sequence, / the function the thread will run / &i/ send the parameter's address to the function */); } /* Wait till threads are complete and join before main continues */ for (i = 0; i pthread_join(tid[i], NULL); } return 0; } /* The thread will begin control in this function */ void Print_Sequence(void param) { int i,j=(int)param; printf("j=%d\n",(*j)); int max; pthread_mutex_lock(&lett[0]); pthread_mutex_lock(&lett[1]); for (i = 1; i <= 10; i++) { max=(int) (8*rand()/(RAND_MAX+1.0)); Sleep_rand( max); printf("A"); } pthread_mutex_unlock(&lett[0]); pthread_mutex_lock(&lett[2]); for (i = 1; i <= 10; i++) { max=(int) (2*rand()/(RAND_MAX+1.0)); Sleep_rand( max); printf("B"); } for (i = 1; i <= 10; i++) { max=(int) (15*rand()/(RAND_MAX+1.0)); Sleep_rand( max); printf("C"); } pthread_mutex_unlock(&lett[1]); pthread_mutex_unlock(&lett[2]); pthread_exit(0); } and the o/p is like : AAAAAAAAAABBBBBBBBBBCCCCCCCCCCAAAAAAAAAABBBBBBBBBBCCCCCCCCCCAAAAAAAAAABBBBBBBBBBCCCCCCCCCC COULD ANYONE PLEASE EXPLAIN WHAT IS THE WRONG WITH CODE ??

    Read the article

  • Structs, strtok, segmentation fault

    - by FILIaS
    I'm trying to make a programme with structs and files.The following is just a part of my code(it;s not all). What i'm trying to do is: ask the user to write his command. eg. delete John eg. enter John James 5000 ipad purchase. The problem is that I want to split the command in order to save its 'args' for a struct element. That's why i used strtok. BUT I'm facing another problem in who to 'put' these on the struct. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 char command[1500]; struct catalogue { char short_name[50]; char surname[50]; signed int amount; char description[1000]; }*catalog[MAX]; int main ( int argc, char *argv[] ) { int i,n; char choice[3]; printf(">sort1: Print savings sorted by surname\n"); printf(">sort2: Print savings sorted by amount\n"); printf(">search+name:Print savings of each name searched\n"); printf(">delete+full_name+amount: Erase saving\n"); printf(">enter+full_name+amount+description: Enter saving \n"); printf(">quit: Update + EXIT program.\n"); printf("Choose your selection:\n>"); gets(command); //it save the whole command /*in choice it;s saved only the first 2 letters(needed for menu choice again)*/ strncpy(choice,command,2); choice[2]='\0'; char** args = (char**)malloc(strlen(command)*sizeof(char*)); memset(args, 0, sizeof(char*)*strlen(command)); char* curToken = strtok(command, " \t"); for (n = 0; curToken != NULL; ++n) { args[n] = strdup(curToken); curToken = strtok(NULL, " \t"); *catalog[n]->short_name=*args[1]; *catalog[n]->surname=args[2]; catalog[n]->amount=atoi(args[3]); *catalog[n]->description=args[4]; } return 0; } I get a warning (warning: assignment makes integer from pointer without a cast) for the lines: *catalog[n]->short_name=*args[1]; *catalog[n]->surname=args[2]; *catalog[n]->description=args[4]; As a result, after running the program i get a Segmentation Fault... Any help? Any ideas?

    Read the article

  • Error building C program

    - by John
    Here are my 2 source files: main.c: #include <stdio.h> #include "part2.c" extern int var1; extern int array1[]; int main() { var1 = 4; array1[0] = 2; array1[1] = 4; array1[2] = 5; array1[3] = 7; display(); printf("---------------"); printf("Var1: %d", var1); printf("array elements:"); int x; for(x = 0;x < 4;++x) printf("%d: %d", x, array1[x]); return 0; } part2.c #include <stdio.h> int var1; int array1[4]; void display(void); void display(void) { printf("Var1: %d", var1); printf("array elements:"); int x; for(x = 0;x < 4;++x) printf("%d: %d", x, array1[x]); } When i try to compile the program this is what i get: Ld /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug/Test normal x86_64 cd /Users/John/Xcode/Test setenv MACOSX_DEPLOYMENT_TARGET 10.7 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk -L/Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug -F/Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug -filelist /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Intermediates/Test.build/Debug/Test.build/Objects-normal/x86_64/Test.LinkFileList -mmacosx-version-min=10.7 -o /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug/Test ld: duplicate symbol _display in /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Intermediates/Test.build/Debug/Test.build/Objects-normal/x86_64/part2.o and /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Intermediates/Test.build/Debug/Test.build/Objects-normal/x86_64/main.o for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) I am using Xcode and both files are inside of a C project called Test What is causing the error and how do i fix it?

    Read the article

  • Calling cdecl Functions That Have Different Number of Arguments

    - by KlaxSmashing
    I have functions that I wish to call based on some input. Each function has different number of arguments. In other words, if (strcmp(str, "funcA") == 0) funcA(a, b, c); else if (strcmp(str, "funcB") == 0) funcB(d); else if (strcmp(str, "funcC") == 0) funcC(f, g); This is a bit bulky and hard to maintain. Ideally, these are variadic functions (e.g., printf-style) and can use varargs. But they are not. So exploiting the cdecl calling convention, I am stuffing the stack via a struct full of parameters. I'm wondering if there's a better way to do it. Note that this is strictly for in-house (e.g., simple tools, unit tests, etc.) and will not be used for any production code that might be subjected to malicious attacks. Example: #include <stdio.h> typedef struct __params { unsigned char* a; unsigned char* b; unsigned char* c; } params; int funcA(int a, int b) { printf("a = %d, b = %d\n", a, b); return a; } int funcB(int a, int b, const char* c) { printf("a = %d, b = %d, c = %s\n", a, b, c); return b; } int funcC(int* a) { printf("a = %d\n", *a); *a *= 2; return 0; } typedef int (*f)(params); int main(int argc, char**argv) { int val; int tmp; params myParams; f myFuncA = (f)funcA; f myFuncB = (f)funcB; f myFuncC = (f)funcC; myParams.a = (unsigned char*)100; myParams.b = (unsigned char*)200; val = myFuncA(myParams); printf("val = %d\n", val); myParams.c = (unsigned char*)"This is a test"; val = myFuncB(myParams); printf("val = %d\n", val); tmp = 300; myParams.a = (unsigned char*)&tmp; val = myFuncC(myParams); printf("a = %d, val = %d\n", tmp, val); return 0; } Output: gcc -o func func.c ./func a = 100, b = 200 val = 100 a = 100, b = 200, c = This is a test val = 200 a = 300 a = 600, val = 0

    Read the article

  • due at midnight - program compiles but has logic error(s)

    - by Leslie Laraia
    not sure why this program isn't working. it compiles, but doesn't provide the expected output. the input file is basically just this: Smith 80000 Jones 100000 Scott 75000 Washington 110000 Duffy 125000 Jacobs 67000 Here is the program: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * * @author Leslie */ public class Election { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here File inputFile = new File("C:\\Users\\Leslie\\Desktop\\votes.txt"); Scanner in = new Scanner(inputFile); int x = 0; String line = ""; Scanner lineScanner = new Scanner(line); line = in.nextLine(); while (in.hasNextLine()) { line = in.nextLine(); x++; } String[] senatorName = new String[x]; int[] votenumber = new int[x]; double[] votepercent = new double[x]; System.out.printf("%44s", "Election Results for State Senator"); System.out.println(); System.out.printf("%-22s", "Candidate"); //Prints the column headings to the screen System.out.printf("%22s", "Votes Received"); System.out.printf("%22s", "%of Total Votes"); int i; for(i=0; i<x; i++) { while(in.hasNextLine()) { line = in.nextLine(); String candidateName = lineScanner.next(); String candidate = candidateName.trim(); senatorName[i] = candidate; int votevalue = lineScanner.nextInt(); votenumber[i] = votevalue; } } votepercent = percentages(votenumber, x); for (i = 0; i < x; i++) { System.out.println(); System.out.printf("%-22s", senatorName[i]); System.out.printf("%22d", votenumber[i]); System.out.printf("%22.2f", votepercent[i]); System.out.println(); } } public static double [] percentages(int[] votenumber, int z) { double [] percentage = new double [z]; double total = 0; for (double element : votenumber) { total = total + element; } for(int i=0; i < votenumber.length; i++) { int y = votenumber[i]; percentage[i] = (y/total) * 100; } return percentage; } }

    Read the article

  • Telephone Directory

    - by Mizukage of Meron 5
    I need your help. We are ask to make a telephone directory program that asks your name, address, and telephone number. If the name you entered already exists, it will display that it already exists. This is what i have so far... #include<stdio.h> #include<conio.h> struct file { char name[25],address[25]; double telno; }; char tempname[25],tempadd[25]; double tempnum; int x; int choice; FILE *fp; main() { struct file rec; clrscr(); fp=fopen("TelDir.txt","a+"); while(!feof(fp)) { fscanf(fp,"%s %s %.0lf,&tempname,&tempadd,&tempnum); printf("\n%s\t\t%s\t\t\t%.0lf",tempname,tempadd,tempnum); printf("\nEnter Name: "); gets(rec.name); if(strcmp(rec.name,tempname)==1) { printf("\n\nALREADY EXIST!"); printf("\n%s\t\t%s\t\t\t%.0lf",tempname,tempadd,tempnum); getch(); } else { printf("Enter Address: "); scanf("%s",&rec.address); printf("Enter your Telephone No.: "); scanf("%lf",&rec.telno); printf("%s\t\t%s\t\t%\t\t0lf",rec.name,rec.address,rec.telno); fprintf(fp,"%s %s %.0lf\n",rec.name,rec.address,rec.telno); } } fclose(fp); getch(); } But this thing doesn't work. I don't know where the error is. Can someone help me on this? I would really appreciate if you could help me somehow.

    Read the article

  • How can I convert this C Calendaer Code into a Objective-C syntax and have it work with matrixes

    - by Alec Niemy
    #define TRUE 1 #define FALSE 0 int days_in_month[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; char *months[]= { " ", "\n\n\nJanuary", "\n\n\nFebruary", "\n\n\nMarch", "\n\n\nApril", "\n\n\nMay", "\n\n\nJune", "\n\n\nJuly", "\n\n\nAugust", "\n\n\nSeptember", "\n\n\nOctober", "\n\n\nNovember", "\n\n\nDecember" }; int inputyear(void) { int year; printf("Please enter a year (example: 1999) : "); scanf("%d", &year); return year; } int determinedaycode(int year) { int daycode; int d1, d2, d3; d1 = (year - 1.)/ 4.0; d2 = (year - 1.)/ 100.; d3 = (year - 1.)/ 400.; daycode = (year + d1 - d2 + d3) %7; return daycode; } int determineleapyear(int year) { if(year% 4 == FALSE && year%100 != FALSE || year%400 == FALSE) { days_in_month[2] = 29; return TRUE; } else { days_in_month[2] = 28; return FALSE; } } void calendar(int year, int daycode) { int month, day; for ( month = 1; month <= 12; month++ ) { printf("%s", months[month]); printf("\n\nSun Mon Tue Wed Thu Fri Sat\n" ); // Correct the position for the first date for ( day = 1; day <= 1 + daycode * 5; day++ ) { printf(" "); } // Print all the dates for one month for ( day = 1; day <= days_in_month[month]; day++ ) { printf("%2d", day ); // Is day before Sat? Else start next line Sun. if ( ( day + daycode ) % 7 > 0 ) printf(" " ); else printf("\n " ); } // Set position for next month daycode = ( daycode + days_in_month[month] ) % 7; } } int main(void) { int year, daycode, leapyear; year = inputyear(); daycode = determinedaycode(year); determineleapyear(year); calendar(year, daycode); printf("\n"); } This code generates a calendar of the inputed year in the terminal. my question is how can i convert this into a Objective-C syntax instead of this C syntax. im sure this is simple process but im quite of a novice to objective - c and i need it for a cocoa project. this code outputs the calendar as a continuously series of strings until the last month hits. soo instead of creating the calendar in the terminal how can i input the calendar a series of NSMatrixes depend on the inputed year. hope somone can help me with this thanks or every helps (you be in the credits of the finished program) :) (the calendar is just a small part of the program i making and it is one of the important parts!!)

    Read the article

  • Clear data at serial port in Linux in C?

    - by ipkiss
    Hello guys, I am testing the sending and receiving programs with the code as The main() function is below: include include include include include include include "read_write.h" int fd; int initport(int fd) { struct termios options; // Get the current options for the port... tcgetattr(fd, &options); // Set the baud rates to 19200... cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); // Enable the receiver and set local mode... options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; // Set the new options for the port... tcsetattr(fd, TCSANOW, &options); return 1; } int main(int argc, char **argv) { fd = open("/dev/pts/2", O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { perror("open_port: Unable to open /dev/pts/1 - "); return 1; } else { fcntl(fd, F_SETFL, 0); } printf("baud=%d\n", getbaud(fd)); initport(fd); printf("baud=%d\n", getbaud(fd)); char sCmd[254]; sCmd[0] = 0x41; sCmd[1] = 0x42; sCmd[2] = 0x43; sCmd[3] = 0x00; if (!writeport(fd, sCmd)) { printf("write failed\n"); close(fd); return 1; } printf("written:%s\n", sCmd); usleep(500000); char sResult[254]; fcntl(fd, F_SETFL, FNDELAY); if (!readport(fd,sResult)) { printf("read failed\n"); close(fd); return 1; } printf("readport=%s\n", sResult); close(fd); return 0; } read_write.h: #include <stdio.h> /* Standard input/output definitions */ include /* String function definitions */ include /* UNIX standard function definitions */ include /* File control definitions */ include /* Error number definitions */ include /* POSIX terminal control definitions */ int writeport(int fd, char *chars) { int len = strlen(chars); chars[len] = 0x0d; // stick a after the command chars[len+1] = 0x00; // terminate the string properly int n = write(fd, chars, strlen(chars)); if (n < 0) { fputs("write failed!\n", stderr); return 0; } return 1; } int readport(int fd, char *result) { int iIn = read(fd, result, 254); result[iIn-1] = 0x00; if (iIn < 0) { if (errno == EAGAIN) { printf("SERIAL EAGAIN ERROR\n"); return 0; } else { printf("SERIAL read error %d %s\n", errno, strerror(errno)); return 0; } } return 1; } and got the issue: In order to test with serial port, I used the socat (https://help.ubuntu.com/community/VirtualSerialPort ) to create a pair serial ports on Linux and test my program with these port. The first time the program sends the data and the program receives data is ok. However, if I read again or even re-write the new data into the serial port, the return data is always null until I stop the virtual serial port and start it again, then the write and read data is ok, but still, only one time. (In the real case, the sending part will be done by another device, I am just taking care of the reading data from the serial port. I wrote both parts just to test my reading code.) Does anyone have any ideas? Thanks a lot.

    Read the article

  • Problem in transfering file from server to client using C sockets

    - by coolrockers2007
    I want to ask, why I cannot transfer file from server to client? When I start to send the file from server, the client side program will have problem. So, I spend some times to check the code, But I still cannot find out the problem Can anyone point out the problem for me? CLIENTFILE.C #include stdio.h #include stdlib.h #include time.h #include netinet/in.h #include fcntl.h #include sys/types.h #include string.h #include stdarg.h #define PORT 5678 #define MLEN 1000 int main(int argc, char *argv []) { int sockfd; int number,message; char outbuff[MLEN],inbuff[MLEN]; //char PWD_buffer[_MAX_PATH]; struct sockaddr_in servaddr; FILE *fp; int numbytes; char buf[2048]; if (argc != 2) fprintf(stderr, "error"); if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) fprintf(stderr, "socket error"); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) fprintf(stderr, "connect error"); if ( (fp = fopen("/home/na/nall9047/write.txt", "w")) == NULL){ perror("fopen"); exit(1); } printf("Still NO PROBLEM!\n"); //Receive file from server while(1){ numbytes = read(sockfd, buf, sizeof(buf)); printf("read %d bytes, ", numbytes); if(numbytes == 0){ printf("\n"); break; } numbytes = fwrite(buf, sizeof(char), numbytes, fp); printf("fwrite %d bytes\n", numbytes); } fclose(fp); close(sockfd); return 0; } SERVERFILE.C #include stdio.h #include fcntl.h #include stdlib.h #include time.h #include string.h #include netinet/in.h #include errno.h #include sys/types.h #include sys/socket.h #includ estdarg.h #define PORT 5678 #define MLEN 1000 int main(int argc, char *argv []) { int listenfd, connfd; int number, message, numbytes; int h, i, j, alen; int nread; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; FILE *in_file, *out_file, *fp; char buf[4096]; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) fprintf(stderr,"listen error") ; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) fprintf(stderr,"bind error") ; alen = sizeof(struct sockaddr); connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &alen); if (connfd < 0) fprintf(stderr,"error connecting") ; printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr)); fp = fopen ("/home/na/nall9047/read.txt", "r"); // open file stored in server if (fp == NULL) { printf("\nfile NOT exist"); } //Sending file while(!feof(fp)){ numbytes = fread(buf, sizeof(char), sizeof(buf), fp); printf("fread %d bytes, ", numbytes); numbytes = write(connfd, buf, numbytes); printf("Sending %d bytes\n",numbytes); } fclose (fp); close(listenfd); close(connfd); return 0; }

    Read the article

  • C socket: problem with connect() and/or accept() between clients. 111: Connection refused

    - by Fantastic Fourier
    Hello ladies and gents, I'm having a bit of problem with accept(). I have a multiple clients and one server. The clients can connect and communicate just fine with server. But at one point, I need some clients to be directly connected to each other and I'm having a bit of difficulty there. The clients have bunch of threads going on, where one of them is handle_connection() and it has a while(1), looping forever to listen() and accept() whatever incoming connections. Whenever a client tries to connect() to other client, connect() returns an error, 111: Connection Refused. I know I have the right IP address and right port (I have specified a port just for between-client connections). The client that is waiting for connection doesn't notice anything, no new connection, nada. I copied some parts of the code, in hopes that someone can point out what I'm doing wrong. Thanks for any inputs! This is all client side code. void * handle_connections(void * arg) is a thread that loops forever to accept() any incoming connections. My server has a very similar thang going on and it works very well. (not sure why it doesn't work here..) This is the part of client that is waiting for a new incoming connection. int handle_request(void * arg, struct message * msg) is called at one point during program and tries to connect to a client that is specified in struct message * msg which includes struct sockaddr_in with IP address and port number and whatever. #define SERVER_PORT 10000 #define CLIENT_PORT 3456 #define MAX_CONNECTION 20 #define MAX_MSG 50 void * handle_connections(void * arg) { struct fd_info * info; struct sockaddr_in client_address; struct timeval timeout; fd_set readset, copyset; bzero((char * ) &client_address, sizeof(client_address)); // copy zeroes into string client_address.sin_family = AF_INET; client_address.sin_addr.s_addr = htonl(INADDR_ANY); client_address.sin_port = htons(CLIENT_PORT); sockfd = socket(AF_INET, SOCK_STREAM, 0); rv = listen(sockfd,MAX_CONNECTION); while(1) { new_sockfd = accept(sockfd, (struct sockaddr *) &client_address, &client_addr_len); //blocks if (new_sockfd < 0) { printf("C: ERROR accept() %i: %s \n", errno, strerror(errno)); sleep(2); } else { printf("C: accepted\n"); FD_SET(new_sockfd, &readset); // sets bit for new_sockfd to list of sockets to watch out for if (maxfd < new_sockfd) maxfd = new_sockfd; if (minfd > new_sockfd) minfd = new_sockfd; } //end if else (new_sockfd) } // end of the forever while loop } int handle_request(void * arg, struct message * msg) { char * cname, gname, payload; char * command[3]; int i, rv, sockfd, client_addr_len; struct sockaddr_in client_address; struct fd_info * info; info = (struct fd_info *) arg; sockfd = info->sock_fd; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf("HR: ERROR socket() %i: %s \n", errno, strerror(errno)); break; } else if (sockfd > 0) { printf("HR: new socks is %i \n", sockfd); printf("HR: sin_family is %i: %i\n", msg->peer.client_address.sin_family, msg->peer.client_address.sin_port); //************************************************************* //this is the part that returns error 111: Connection refused!!! //************************************************************* rv = connect(sockfd, (struct sockaddr *) &msg->peer.client_address, sizeof(struct sockaddr)); if (rv == -1) { printf("HR: ERROR: connect() %i: %s \n", errno, strerror(errno)); printf("HR: at %li \n", msg->peer.client_address.sin_addr.s_addr); break; } else if (rv > 0) { info->max_fd = sockfd; printf("HR: connected successfully!! \n"); } } }

    Read the article

  • Display problem after deletion in linked list in C

    - by LuckySlevin
    Hi, actually this was another problem but it changed so I decided to open a new question. My code is typedef struct inner_list { int count; char word[100]; inner_list*next; } inner_list; typedef struct outer_list { char word [100]; inner_list * head; int count; outer_list * next; } outer_list; void delnode(outer_list **head,char num[100])//thanks to both Nir Levy and Jeremy P. { outer_list *temp, *m; m=temp=*head; /*FIX #1*/ while(temp!=NULL) { if(strcmp(temp->word,num)==0) { if(temp==*head) { delinner(temp->head); /* FIX#2 */ *head=temp->next; free(temp); return; } else { delinner(temp->head); /* FIX#2 */ m->next=temp->next; free(temp); return; } } else { m=temp; temp= temp->next; } } printf(" ELEMENT %s NOT FOUND ", num); } void delinner(inner_list *head) { /* FIX#2 */ inner_list *temp; temp=head; while(temp!=NULL) { head=temp->next; free(temp); temp=head; } } void delnode2(outer_list *up,inner_list **head,char num[100]) { inner_list *temp2,*temp, *m; outer_list *p; p = up; while(p!=NULL){m=temp=temp2=p->head; while(temp!=NULL) { if(strcmp(temp->word,num)==0) { if(temp==(*head)) { *head=temp->next; free(temp); return; } else { m->next=temp->next; free(temp); return; } } else { m=temp; temp= temp->next; } } p=p->next; } printf(" ELEMENT %s NOT FOUND ", num); } void print_node(outer_list *parent_node) { while(parent_node!=NULL){ printf("%s\t%d\t", parent_node->word, parent_node->count); inner_list *child_node = parent_node->head; printf("list: "); if(child_node ==NULL){printf("BUARADA");} while (child_node != NULL) { printf("%s-%d", child_node->word,child_node->count); child_node = child_node->next; if (child_node != NULL) { printf("->"); } } printf("\n"); parent_node = parent_node->next; } } While deleting an element from outer list I am also trying the delete the same element from inner_list too. For example: - Let's say aaa is an element of outer_list linked list and let's point it with outer_list *p - This aaa can also be in an inner_list linked list too. (it can be in p-head or another innerlist.) Now, the tricky part again. I tried to apply the same rules with outer_list deletion but whenever i delete the head element of inner_list it gives an error. Where is the wrong thing in print_node or delnode2?

    Read the article

  • Why does glGetString returns a NULL string

    - by snape
    I am trying my hands at GLFW library. I have written a basic program to get OpenGL renderer and vendor string. Here is the code #include <GL/glew.h> #include <GL/glfw.h> #include <cstdio> #include <cstdlib> #include <string> using namespace std; void shutDown(int returnCode) { printf("There was an error in running the code with error %d\n",returnCode); GLenum res = glGetError(); const GLubyte *errString = gluErrorString(res); printf("Error is %s\n", errString); glfwTerminate(); exit(returnCode); } int main() { // start GL context and O/S window using GLFW helper library if (glfwInit() != GL_TRUE) shutDown(1); if (glfwOpenWindow(0, 0, 0, 0, 0, 0, 0, 0, GLFW_WINDOW) != GL_TRUE) shutDown(2); // start GLEW extension handler glewInit(); // get version info const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string const GLubyte* version = glGetString (GL_VERSION); // version as a string printf("Renderer: %s\n", renderer); printf("OpenGL version supported %s\n", version); // close GL context and any other GLFW resources glfwTerminate(); return 0; } I googled this error and found out that we have to initialize the OpenGL context before calling glGetString(). Although I have initialized OpenGL context using glfwInit() but still the function returns a NULL string. Any ideas? Edit I have updated the code with error checking mechanisms. This code on running outputs the following There was an error in running the code with error 2 Error is no error

    Read the article

  • Are Vala and desktopcouch ready?

    - by pavolzetor
    Hi, I have started writting rss reader in Vala, but I don't know, what database system should I use, I cannot connect to couchdb and sqlite works fine, but I would like use couchdb because of ubuntu one. I have natty with latest updates public CouchDB.Session session; public CouchDB.Database db; public string feed_table = "feed"; public string item_table = "item"; public struct field { string name; string val; } // constructor public Database() { try { this.session = new CouchDB.Session(); } catch (Error e) { stderr.printf ("%s a\n", e.message); } try { this.db = new CouchDB.Database (this.session, "test"); } catch (Error e) { stderr.printf ("%s a\n", e.message); } try { this.session.get_database_info("test"); } catch (Error e) { stderr.printf ("%s aa\n", e.message); } try { var newdoc = new CouchDB.Document (); newdoc.set_boolean_field ("awesome", true); newdoc.set_string_field ("phone", "555-VALA"); newdoc.set_double_field ("pi", 3.14159); newdoc.set_int_field ("meaning_of_life", 42); this.db.put_document (newdoc); // store document } catch (Error e) { stderr.printf ("%s aaa\n", e.message); } reports $ ./xml_parser rss.xmlCannot connect to destination (127.0.0.1) aa Cannot connect to destination (127.0.0.1) aaa

    Read the article

  • Thread scheduling Round Robin / scheduling dispatch

    - by MRP
    #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <semaphore.h> #define NUM_THREADS 4 #define COUNT_LIMIT 13 int done = 0; int count = 0; int quantum = 2; int thread_ids[4] = {0,1,2,3}; int thread_runtime[4] = {0,5,4,7}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void * inc_count(void * arg); static sem_t count_sem; int quit = 0; ///////// Inc_Count//////////////// void *inc_count(void *t) { long my_id = (long)t; int i; sem_wait(&count_sem); /////////////CRIT SECTION////////////////////////////////// printf("run_thread = %d\n",my_id); printf("%d \n",thread_runtime[my_id]); for( i=0; i < thread_runtime[my_id];i++) { printf("runtime= %d\n",thread_runtime[my_id]); pthread_mutex_lock(&count_mutex); count++; if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\n",my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1) ; }//End For sem_post(&count_sem); // Next Thread Enters Crit Section pthread_exit(NULL); } /////////// Count_Watch //////////////// void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\n", my_id); pthread_mutex_lock(&count_mutex); if (count<COUNT_LIMIT) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\n", my_id); printf("watch_count(): thread %ld count now = %d.\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(NULL); } ////////////////// Main //////////////// int main (int argc, char *argv[]) { int i; long t1=0, t2=1, t3=2, t4=3; pthread_t threads[4]; pthread_attr_t attr; sem_init(&count_sem, 0, 1); /* Initialize mutex and condition variable objects */ pthread_mutex_init(&count_mutex, NULL); pthread_cond_init (&count_threshold_cv, NULL); /* For portability, explicitly create threads in a joinable state */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); pthread_create(&threads[3], &attr, inc_count, (void *)t4); /* Wait for all threads to complete */ for (i=0; i<NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf ("Main(): Waited on %d threads. Done.\n", NUM_THREADS); /* Clean up and exit */ pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(NULL); } I am trying to learn thread scheduling, there is a lot of technical coding that I don't know. I do know in theory how it should work, but having trouble getting started in code... I know, at least I think, this program is not real time and its not meant to be. Some how I need to create a scheduler dispatch to control the threads in the order they should run... RR FCFS SJF ect. Right now I don't have a dispatcher. What I do have is semaphores/ mutex to control the threads. This code does run FCFS... and I have been trying to use semaphores to create a RR.. but having a lot of trouble. I believe it would be easier to create a dispatcher but I dont know how. I need help, I am not looking for answers just direction.. some sample code will help to understand a bit more. Thank you.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >