Initialise mutex globally in C - c

I have some code where two 2 threads modify the value of the same variable but with two different functions. So I decided to use a common mutex. That for: I initialised it globally :
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define perror_pthread(ret, msg) \
do { errno = ret; perror(msg); } while (0)
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /*define a mutex-object */
pthread_mutex_init(&mutex,NULL); /*initialise this mutex object with default values */
I get an error message :
error: expected declaration specifiers or ‘...’ before ‘&’ token
pthread_mutex_init(&mutex,NULL); /*initialise this mutex object with default values */
^
I don't know if that's a good practice, but I feel like both functions should have the same mutex in order to be informed when there is lock

pthread_mutex_init is a function and C forbids expressions (i.e. function calls) at the file scope.
Either use static initializer or put pthread_mutex_init(...) into beginning of main().

Related

How do I use sigaction()? struct sigaction is not defined

I am doing simple sigaction example to practice C, but when I try to compile my code, it claims that struct sigaction doesn't exist [1].
When I checked out some old code I had produced I saw that I had added some POSIX string at the very top of the file [2]. But when I read the manual for sigaction (man 2 sigaction) there is nothing about _POSIX_SOURCE in it, the closest being _POSIX_C_SOURCE which doesn't work. How and when do I know which POSIX is the be used? When I try simple code that others have suggested, which is without the _POSIX_SOURCE it doesn't work.
[1]
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
void sa_handler(int signum)
{
printf("The signal has been replaced with this useless
string!\n");
exit(0);
}
int main(void)
{
struct sigaction sa = {.sa_handler = sa_handler};
int sigret = sigaction(SIGINT, &sa, NULL);
while(1);
return 0;
}
[2]
#define _POSIX_SOURCE
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
void sa_handler(int signum)
{
printf("The signal has been replaced with this useless
string!\n");
exit(0);
}
int main(void)
{
struct sigaction sa = {.sa_handler = sa_handler};
int sigret = sigaction(SIGINT, &sa, NULL);
while(1);
return 0;
}
When I compile the first example the result are these error messages.
sigaction.c: In function ‘main’:
sigaction.c:13:12: error: variable ‘sa’ has initializer but
incomplete type
struct sigaction sa = {.sa_handler = sa_handler};
^~~~~~~~~
sigaction.c:13:29: error: ‘struct sigaction’ has no member named
‘sa_handler’
struct sigaction sa = {.sa_handler = sa_handler};
^~~~~~~~~~
sigaction.c:13:42: warning: excess elements in struct initializer
struct sigaction sa = {.sa_handler = sa_handler};
^~~~~~~~~~
sigaction.c:13:42: note: (near initialization for ‘sa’)
sigaction.c:13:22: error: storage size of ‘sa’ isn’t known
struct sigaction sa = {.sa_handler = sa_handler};
^~
sigaction.c:14:18: warning: implicit declaration of function
‘sigaction’ [-Wimplicit-function-declaration]
int sigret = sigaction(SIGINT, &sa, NULL);
^~~~~~~~~
when I read the manual for sigaction (man 2 sigaction) there is nothing about _POSIX_SOURCE in it
From man sigaction:L
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
From future_test_macros(7):
_POSIX_SOURCE
Defining this obsolete macro with any value is equivalent to
defining _POSIX_C_SOURCE with the value 1.
Since this macro is obsolete, its usage is generally not doc‐
umented when discussing feature test macro requirements in
the man pages.
So _POSIX_SOURCE is equivalent to _POSIX_C_SOURCE 1 and is obsolete.
How and when do I know which POSIX is the be used?
From man future_test_macros:
Specification of feature test macro requirements in manual pages
When a function requires that a feature test macro is defined, the
manual page SYNOPSIS typically includes a note [....]
So you should check SYNOPSIS section in the manual page of the function/feature you are interested in. For example for man sigaction:
sigaction(): _POSIX_C_SOURCE
siginfo_t: _POSIX_C_SOURCE >= 199309L
So you need to define _POSIX_C_SOURCE for sigaction() and _POSIX_C_SOURCE greater or equal to the value of 199309 for siginfo_t.
You need to define a positive integer for _POSIX_C_SOURCE. For sigaction, it needs to be atleast:
#define _POSIX_C_SOURCE 199309L
Look the the documentation for which POSIX version to use.
You need to add <features.h> before <signals.>, as the features.h contains #define _POST_C_SOURCE with latest value for compatibility purpose.

expected ')' before '*' token, can't seem to find error

So whenever I try to run my Makefile on my server, it always gives me the error is "Memory.c: 9 error: expected ')' before '*' token. But when I try to run it on my own computer, it works just fine. I've been trying to figure out what is wrong but can't seem to find it.
I've attached the 3 files that are used in this part of my program. Memory.c, Memory.h and ProcessInput.h.
This is Memory.c
/* Initializes memory */
#include <stdio.h>
#include <stdlib.h>
#include "memory.h"
void initializeMemory(memory** memArray, int memSize)
{
// Allocating space for memory array
*memArray = malloc(memSize * sizeof(memory));
if(*memArray == NULL)
{
fprintf(stderr, "Error allocating space for array of memory" );
exit(1); // exit(1) = Unsuccessful exit
}
// Initializing the contents within memory array
int i = 0;
for(i = 0; i < memSize; i ++)
{
((*memArray)[i]).occupied = false;
}
}
and this is Memory.h
// Definitions for Memory.c
#define bool int
#define true 1
#define false 0
#include "ProcessInput.h"
// Include guards to prevent redefinition of struct
#ifndef MEMORY_H
#define MEMORY_H
typedef struct memoryDetail
{
process process;
bool occupied;
} memory;
#endif
// Function declaration for memory.c
void initializeMemory(memory** memArray, int memSize);
the only thing used from ProcessInput.h is the process structure defined in ProcessInput.h
This is ProcessInput.h
// Include guards to prevent redefinition of struct
#ifndef PROCESSDETAIL_H
#define PROCESSDETAIL_H
typedef struct processDetail
{
int timeCreated;
int processID;
int memorySize;
int jobTime;
} process;
#endif
// function declarations for ProcessInput.c
void processInput(int* maxSize, int* count, process** processes, char* fileName);
I'm not too sure why it's giving me the error. I don't know where I'm supposed to be putting a missing right brace. Any advice is much appreciated!
edit: As informed, these are the following questions that I looked at but to not avail.
error: expected ‘)’ before ‘*’ token
Multiple of same error while compiling "error: expected ')' before '*' token
http://www.dreamincode.net/forums/topic/288956-error-expected-before-token/
thanks everyone for the help!
#include "memory.h" is different to #include "Memory.h" (i.e. C is case sensitive)
If you tried #include "myfile.h" instead of #include "MyFile.h" the error may be more obvious. In this case it just happens that the compiler finds the system memory.h.
<memory.h> is a header from C library of pre-standard era. It is quite possible that your standard library still provides it and the compiler takes that one instead of yours.
Try renaming your header file and see if it changes anything.

declare struct timeval time inside a function

I have done some search about problems when using time.h to obtain a random seed initialization. Particularly in my case, I want to place the time outside the main function.
Based on the comments I made some changes. After including twice in the include as and , these errors and warning went off:
too few arguments to function ‘random’
implicit declaration of function ‘srandom’ [-Wimplicit-function-declaration]
too few arguments to function ‘random’
Once I declared the code as:
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <unistd.h>
#include <math.h>
int main(void)
{
struct timeval time;
...
}
It works, however it has to move outside main. But if I change to:
#include <sys/time.h>
struct timeval time;
int main(void)
{
...
}
It gives me the error:
‘time’ redeclared as different kind of symbol
In my case the implementation I am working on is in C not in C++. When I try to move the code to a function in order to receive a different random number every time my function is called, some other errors happen:
double myRandom(double dAverage,double dStddev);
double myRandom(double dAverage,double dStddev){
int iRandom1, iRandom2;
double dRandom1, dRandom2,result;
long int liSampleSize;
iRandom1=(random());
dRandom1=(double)iRandom1 /2147483647;
iRandom2=(random());
dRandom2=(double)iRandom2 /2147483647;
result= dAverage + dStddev * sqrt(-2.0 * log(dRandom1))*cos(6.28318531 * dRandom2);
return(result);
}
int main(void){
...
struct timeval time;
gettimeofday(&time, NULL);
srandom((unsigned int) time.tv_usec);
for (i=0; i<liSampleSize;i++)
{ result=myRandom(dAverage,dStddev);
}
}
Apparently it should be working. Has somebody any idea what is wrong here. All comments are highly appreciated.
Update: Then, taking srandom out of myRandom makes the generated values as expected. So, it worked!
The first error is related to time.h. Including it introduces some instance called time to your global namespace.
The second is most likely because you haven't included stdlib.h.

Cannot compile with waitid() and P_PID

I am new to Linux. I am trying to use waitid() to wait for a child process.
When I try to compile a file including the following lines using gcc:
id_t cpid = fork();
siginfo_t status;
waitid(P_PID, cpid, &status, WEXITED);
The following error was generated:
error: ‘P_PID’ undeclared (first use in this function)
I included the following libraries:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <time.h>
Did I miss something?
Another question is that how can I use WIFSIGNALED() to retrieve information from type siginfo_t?
You need to include <sys/wait.h> and define _XOPEN_SOURCE, as documented in the manual.
The WIFSIGNALED macro must be used with the integer status obtained from wait, waitpid or waitid. In the case of waitpid, the status is available as the si_status member of the siginfo_t structure. In other words, you would use WIFSIGNALED(info.si_status), info being a structure of type siginfo_t whose address you previously passed to waitid().

Error: No previous prototype for function. Why am I getting this error?

// screen.h
#ifndef screen_h
#define screen_h
#define MAC 1
#define WIN 2
#define LNX 3
#ifdef PLATFORM
# undef PLATFORM
#endif
#define PLATFORM MAC
void screen_init();
#endif
// screen.c
#include <string.h>
#include <stdlib.h>
#include "screen.h"
#if PLATFORM == MAC
#include <curses.h>
void screen_init(){
erase();
}
#endif
I don't understand why it is not seeing my prototype in screen.h
Any suggestions/hints are appreciated!
ISO/IEC 9899:TC2 - 6.2.1.2:
A function prototype is a declaration of a function that declares the types of its parameters.
An empty argument list in a function declaration indicates that the number and type of parameters is not known. You must explicitly indicate that the function takes no arguments by using the void keyword. Otherwise your function declaration does not count as a valid prototype.
void screen_init(void);
I met this similar error minutes ago. After i'd added the relatived function declaration in head file, error's gone.
Also, some said that canceling the compile option '-Wmissing-prototypes' should work, but i didn't have tried that. Good luck.
I just had this problem today.
I defined a function that just used internally
void func(void) {
}
int main(void) {
func();
}
This will give me that warning.
I had to add the prototype at the beginning of the file to get rid of the warning.
void func(void);
void func(void) {
}
int main(void) {
func();
}

Resources