FAQ Database Discussion Community


How pthread_mutex_unlock distinguish threads?

c++,c,linux,posix,mutex
Only the owner of mutex can unlock it. But how mutex distinguish thread that locked it? Does threads have any distinctive features in Linux?

Copying existing function into memory buffer

c++,c,linux,posix
I'm trying to load a function into a mapped memory buffer and call it later so I've made a test case to try out: auto func() -> void{ asm( "nop;" "nop;" "nop;" "nop;" ); } auto main(int argc, char *argv[]) -> int{ void *exec_mem = mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE...

Shared memory and POSIX semaphores

c,concurrency,posix,ipc
I wrote simple consumer-producer program in C. It is working fine while I have 1 producer and 1 consumer. But it is acting strange when I increase number of consumers. I start the producer process Producer is producing I start the consumer process Consumer is consuming and producer is producing...

Linux 3.13 Kernel Module set procfile_read end of file condition

c,linux,module,kernel,posix
I am writing a Kernel Module for Linux 3.13 where the procfile_read function prototype is defined as: static ssize_t procfile_read(struct file *file, char __user *buffer, size_t count, loff_t * data) This is different from every resource I can find online, such as http://linux.die.net/lkmpg/x769.html, where the function prototype was different for...

how to list all the .txt files in the current directory?

c,file,posix
I do know how to read all the files from the current directory by opening directory "./" and then using readdir. But, how do I list only .txt files or any other specific extension? DIR *p; struct dirent *pp; p = opendir ("./"); if (p != NULL) { while ((pp...

Waitpid and synchronization issues

c++,linux,multithreading,process,posix
I created a simple Process class that mimics std::thread. It is supposed to work on linux only. struct Process { Process(/*...*/) { /* fork + join, initialize m_pid */ } ~Process() { assert(!joinable()); } bool joinable() const { return m_pid != 0; } void join() { assert (joinable()); int status;...

Error on dlclose: “shared objects still referenced”

linux,shared-libraries,posix,qnx
I have the following error on a dlclose()'d .so: "Shared objects still referenced". I didn't find too much information about it. Did you have such a problem before? What kind of programming errors (or compiling options?) can cause this? The only thing I tried is to find if MY module...

Notification Child to Father Thread in C

c,multithreading,posix
I'm working with a Thread Pool. So I'm looking for a simple and efficient way to notify the father that a child has finished its job and that it's ready to work on another. Is there a way to do this? The use of Condition Variable is only half-duplex (from...

How can heredocs be used with xargs?

find,posix,xargs,heredoc,ed
Background I'm looking to strip any # TODO comments from some python source code files output by git archive before sending it off. I'm looking to do so from a script that will be run from a variety of *nix OSes, so it should be as POSIX-compliant as possible. I'm...

gethostbyname dual network interfaces, select which one to use

c,networking,dns,posix,gethostbyname
I have a c-program that needs to connect to a server and send a tcp payload and wait for the response. This works well for normal use but since I have two different network interfaces, let us call them if0 and if1 on the computer running the program, sometimes one...

What is included in C Standard library?

c,linux,posix,standards,language-lawyer
I will give an example from The GNU C Library documentation: 13.1 Opening and Closing Files This section describes the primitives for opening and closing files using file descriptors. The open and creat functions are declared in the header file fcntl.h, while close is declared in unistd.h. My question is:...

Initialising a semaphore in C

c,posix
I'm trying to create a generic function to create a semaphore in C, but i'm unsure about the value of the third argument, named mode_t mode. I read the read/write are the standard permissions, and i would like to go with that. What's the value i need to use ?...

Where does the recursive variable expansion in bash/shell numeric contexts come from?

bash,shell,posix,ksh,arithmetic-expressions
The POSIX spec states with regard to Arithmetic Expansion that [i]f the shell variable x contains a value that forms a valid integer constant, optionally including a leading plus or minus sign, then the arithmetic expansions "$((x))" and "$(($x))" shall return the same value. Which is a reasonable shortcut and...

Why can “dash -c ':'” fail with dash 0.5.8 built from source?

shell,ubuntu,posix,dash
With a dash binary compiled from source (version 0.5.8, available at http://gondor.apana.org.au/~herbert/dash/files/dash-0.5.8.tar.gz), executing dash -c ':' fails with dash: 1: :: Permission denied This means that constructs such as case foo in *bar*) : do_stuff ;; *) : ;; esac fails, which breaks a lot of scripts. Why do the...

Implementing chat client following Beej's guide to network programming

c,sockets,network-programming,posix
I'm trying to learn network programming by following Beej's guide. I have compiled the server in section 7.2, that's using select(), and now I'm trying to write a client for that server, so I could open two terminals on my machine and be able to chat. I have started off...

Can not read from opened file

c,linux,file,io,posix
The file exists and I have just read from it in another function. The other function closes the file. Now, my workwith() tries to open it and read from it. My code: if (access(path_file, F_OK) != -1) { // file exists *mfs_desc = open(path_file, O_WRONLY | O_RDONLY, 0600); if (*mfs_desc...

C - does read() add a '\0'?

c,unix,io,posix,unbuffered
Does it have to? I've always been fuzzy on this sort of stuff, but if I have something like: char buf[256]; read(fd, buf, 256); write(fd2, buf, 256); Is there potential for error here, other than the cases where those functions return -1? If it were to only read 40 characters,...

Subtract time in r, forcing unit of results to minutes [duplicate]

r,posix,posixct
This question already has an answer here: Getting consist units from diff command in R 4 answers I successfully subtracted two POSIXct cols of df1 (below). However, since the time differences are >= 1 hour in all rows, R gives the results in hours. I know that this make...

pthread_mutex_wait multiple producer and consumer

c++,multithreading,pthreads,posix,producer-consumer
I was going through this and this link. Basically, they are discussing why classical single threaded producer consumer design (with signal and wait does not work for multi-producer scenario). I have one doubt which has been bugging me - Argument made by author Consider reference code char queue[MAX]; //global int...

regex to match first instance of a word but only when preceeded by match from another pattern

regex,postgresql,posix
I've found some info on finding the first instance of a word in a string, but I'm trying to find the first instance of a word (two, actually, but in separate calls) only when it is preceded by some very specific text (an IP address delimited by underscores) that varies...

Software interrupts on AVR

posix,interrupt,system-calls,avr,syscall
I understand that x86 machine code can make POSIX system calls using software interrupts (by entering a 32-bit value corresponding to a kernel function into the EAX register of the processor and then executing INT 0x80). I'm looking into designing a small Unix-like operating system for the AVR architecture for...

Can POSIX/Linux unlink file entries completely race free?

linux,file-io,path,posix,race-condition
POSIX famously lets processes rename and unlink file entries with no regard as to the effects on others using them, whilst Windows by default raises an error if you even try to touch the timestamps of a directory which has a file handle open somewhere deep inside inside. However Windows...

default field separator for awk

linux,unix,awk,posix,separator
Sorry for this stupid question, searched but not confident is the right answer is found, so the default separator is only space for awk?

Turn std::string into array of char* const*'s

c++,string,shell,vector,posix
I am writing a command shell in C++ using the POSIX api, and have hit a snag. I am executing via execvp(3), so I somehow need to turn the std::string that contains the command into a suitable array of char* consts*'s that can be passed to: int execvp(const char *file,...

Why does POSIX not define a mid-layer socket API?

c,sockets,posix,standard-library
I am looking at socket programming again. I get the details (well, I can copy them from various websites, and I know the code is enabling the Unix low-level procedures), but I don't get the POSIX logic and thinking in its API. Why have they not defined a slightly higher-level...

Is it safe to set IFS for a for loop and then unset it inside the for loop?

linux,shell,unix,posix
Consider the following shell script that I intend to run on any POSIX.1-2004 conformant shell. log() { echo debug: "$*" } A=foo:bar:baz IFS=: for i in $A do log token ">> >>" "$i" done unset IFS # Do more stuff here I want to loop over colon separated values. Within...

Can POSIX named semaphores synchronize threads?

multithreading,synchronization,posix,semaphore
I am looking for a way to synchronize several multi-threaded processes on Linux. C++11-style mutexes only operate among threads within a single process, ans as far as I know, flock doesn't mutually excludes threads of the same process. Therefore, I was thinking of POSIX semaphores. I know that unnamed semaphores...

How can I measure elapsed time when encrypting using openssl in linux by C

linux,posix,libc
How can I calculate the amount of processing time used by a process in C on Linux. Specifically, I want to determine how much time elapses when encrypting a file using openssl.

Producer, consumer POSIX

c,concurrency,posix,ipc
I am trying to write simple producer consumer app using C POSIX semaphores. Consumer: int memoryID; struct wrapper *memory; int main(int argc, char **argv) { srand(time(NULL)); key_t sharedMemoryKey = ftok(".",MEMORY_KEY); if(sharedMemoryKey==-1) { perror("ftok():"); exit(1); } memoryID=shmget(sharedMemoryKey,sizeof(struct wrapper),0); if(memoryID==-1) { perror("shmget(): "); exit(1); } memory = shmat(memoryID,NULL,0); if(memory== (void*)-1) { perror("shmat():");...

How should I simulate sem_wait with a count?

c,posix,semaphore
I'm using semaphore.h and would like to acquire a semaphore if n instead of just one slot is available. Posix does not provide this natively. How can I work around that? I'm bound to using semaphores, no other means of synchronization are possible. I'm pondering using a binary semaphore with...

How do I get current Unix time in nanoseconds in Android Shell?

android,shell,unix,time,posix
I need to get timestamps in nanoseconds in Android shell. Using date command (from busybox and Cyanogenmod) returns to me this: @A001 # date +%s.%N 1819.N The only other working option that I found is using www.timeapi.org. curl -sSw'\n' http://www.timeapi.org/utc/now?\\s.\\N >> ctime_tar.txt However, it requires connection and also takes 0.1...

Is select() + non-blocking write() possible on a blocking pipe or socket?

sockets,unix,pipe,posix,blocking
The situation is that I have a blocking pipe or socket fd to which I want to write() without blocking, so I do a select() first, but that still doesn't guarantee that write() will not block. Here is the data I have gathered. Even if select() indicates that writing is...

A unix system programming project on windows?

c,unix,posix,system
I was given a unix prgramming project (with of cours a use of signal handling and fork()) but i have some issues with my ubuntu and i prefer to work on windows. So is there a solution ? I installed Cygwin but i don't think it will be enough to...

Proper way to create file of size “x” for use with mmap, ect

ios,c,posix
I need to create a file of precisely x bits (which will then be mmap'd). I thought using lseek() or ftruncate() was sufficient, until I saw code from various sources (ex. Mozilla) using fcntl() with F_PREALLOCATE first, then used ftruncate(). From the doc's, I can't ascertain why one would do...

POSIX compliant way to find out if a process with a certain PID is alive

shell,process,posix
I learnt from http://serverfault.com/q/366474 that the following code is a POSIX-compliant way of testing whether a process with PID = $pid is alive. It uses the kill -0 command. # First code sample pid=100 if kill -0 "$pid" 2> /dev/null then echo PID "$pid" is alive. else echo PID "$pid"...

POSIX Bonjour/mDNSResponder test examples report “bind: Address already in use” on Ubuntu, but not Debian

c,sockets,posix,bonjour,mdns
When building the Apple's implementation of mDNS, aka. Bonjour, aka. mDNSResponder for a posix system (http://www.opensource.apple.com/tarballs/mDNSResponder/) [*] On a clean Ubuntu 14.04 build box (with only build-essentials, g++), the compiled examples fail to work, and report "bind: Address already in use". On a clean Debian 7 build box (with only...

Regular expression with POSIX bracket expressions not working in bash

regex,bash,posix
I have this regular expression that works in Rubular value[[:space:]]*=[[[:digit:]]\.]+>([[[:alpha:]][[:space:]]*\/]+) on this text: <option value =12.34.567>London</option> <option value =89.12.345>New York / San Francisco</option> It gives the result: Match 1 1. 12.34.567 2. London Match 2 1. 89.12.345 2. New York / San Francisco Which is what I want. But when...

Compare-and-Swap over POSIX-compliant filesystem objects

algorithm,filesystems,posix,atomic,compare-and-swap
There are several operations which POSIX-compliant operating systems can do atomically with filesystem objects (files and folders). Here is a list of such presumably atomic operations: rename or move file or folder create hardlink create symlink create folder create and open an empty file Is it possible to build Compare-and-Swap...

Optional Cancellation points

multithreading,pthreads,posix
I just want to know the meaning of optional Cancellation point. Like we have mandatory cancellation point which means cancellation point shall occur when any of the functions that comes under mandatory cancellation points is called in a thread. So, is it like for optional one , cancellation point may...

Counting bytes received by posix read()

c,function,serial-port,posix
I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at http://linux.die.net/man/3/read, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

what's the difference between pthread_attr_setschedparam and pthread_setschedparam?

linux,pthreads,posix,scheduling
what's the difference between pthread_attr_setschedparam and pthread_setschedparam? How should I make decision to choose one to use?

I read more than I write in file

c,linux,file,io,posix
I have a file, partitioned in fixed sized blocks. I am copying a test_file.txt into the 3rd block of the file. I read and copied 18 bytes. Then I am trying to copy from the file that very same .txt file I just imported to a newly created .txt, but...

Padding values when converting to larger types in C

c,type-conversion,posix
case 1: int8_t a = -10; int32_t b; b = (int32_t)a; case 2: uint8_t a = 10; uint32_t b; b = (uint32_t)a; What will b be in these two cases? Is there any guarantees? Will the 3 extra bytes during the type conversion be padded with 0? Clarification: larger as...

Safely returning float value in threads

c,posix
i wish to make a thread return a float value. Changing the data type from float to long works fine, but not with float. Any help? Thanks. void * funcFloat(void * arg){ float x = *(float *)arg; printf("Received: %f\n", x); return (void *)x; } ...

Read a struct from file

c,linux,file,io,posix
I am trying to write a struct of 4 unsigned integers in a file and then read it back, but I can not read anything. Here is my code: // create and write values in superblock .. Superblock s; // the struct if(write(file_desc , &superblock , sizeof(Superblock)) == -1) {...

Determining if data is available on TcpStream

networking,posix,rust
I have a std::net::TcpStream. I want to determine if there is data available to be read without actually reading it yet. The only relevant API I can find on TcpStream itself is read which does not provide any guarantees about whether it blocks waiting for data which does not sound...

Linux : pthread_cond_signal() is not working inside a Signal Handler()

c++,c,linux,signals,posix
Summary ----------- 1. In main() am going for pthread_cond_wait(). 2. In signal handler() am waking main() using pthread_cond_signal(). 3. But main() is not coming out from pthread_cond_wait(). What is wrong here? help me out. #include <stdio.h> myclass *myObj = NULL; In main I am trying to wait for a signal:...

Unnamed semaphore POSIX IPC

c,unix,posix,semaphore
I allocated a shared memory segment of the size of an integer. The expected outcome on stdout should be: P: 1 C: 2 But instead it is: C: 1 P: 2 Why is the child process not being blocked until parent is done and has unlocked the shared memory segment?...

Does main() get paused during signal handling?

c,database,connection,posix,daemon
I'm developing a POSIX daemon which reads from a database from time to time. I'd like to close the connection when SIGTERM arrives (e.g. when the system shuts down). When the signal handler is called, is the main() paused until the handler finishes its job? If so and the handler...

Difference in behaviour between whitespace in IFS vs. non-whitespace in IFS

shell,posix
I know that read command splits the input by the characters in the IFS. So if I set IFS as a space then input to the read command is split using space as the delimiter. This is shown below. [[email protected] ~]$ IFS=" " [[email protected] ~]$ read a b c foo...

Does sleep/nanosleep work by utilizing a busy wait scheme?

c++,c,posix,sleep
I am wondering how is sleep/nanosleep internally implemented? Consider this code: { // on a thread other than main() thread while(1) { //do something sleep(1); } } would the CPU be doing constant context switching to check if sleep of 1 sec is done (i.e. an internal busy wait). I...

POSIX behaviour with VTIME and read()

c++,osx,unix,serial-port,posix
After hours spent researching this online, I'm still not quite clear as to how VTIME and read(int fildes, void *buf, size_t nbyte); work together. It seems to me that as soon as read() gets a single byte, then it disregards VTIME. VTIME is only obeyed when no bytes have been...

Bad address with mq_open

c,posix,ipc
I am trying to open a simple queue using mq_open but I keep getting error: "Error while opening ... Bad address: Bad address" And I have no idea why. int main(int argc, char **argv) { struct mq_attr attr; //max size of a message attr.mq_msgsize = MSG_SIZE; attr.mq_flags = 0; //maximum...

Effect of closing descriptor for pipe

pipe,posix,file-descriptor
I have this piece of code which does the same work as ls -l | wc -l. main () { int i; int p[2]; pid_t ret; pipe (p); ret = fork (); if (ret == 0) { close (1); dup (p[1]); close (p[0]); execlp ("ls", "ls", "-l", (char *) 0);...

When are the getnet* functions used?

c,posix
getnetbyaddr, getnetbyname, getnetent, etc. I saw these functions but I still can't find a place where they are used (apart from libc unit tests). What are they useful for and why were they written in the first place?...

converting “1984-03-25 02:00:00” to POSIX gives NA

r,datetime,posix,na
While converting a vector of date-time to POSIXlt, just one particular time "25-Mar-1984-02:00" "is converted to POSIXlt but returns NA! So, this row was getting omitted in my analysis/plots. is.na(as.POSIXlt("25-Mar-1984-02:00",format = "%d-%b-%Y-%H:%M")) is.na(as.POSIXlt("25-Mar-1984-03:00",format = "%d-%b-%Y-%H:%M")) is.na(as.POSIXlt("25-Mar-1984-01:00",format = "%d-%b-%Y-%H:%M")) is.na(as.POSIXlt("24-Mar-1984-02:00",format = "%d-%b-%Y-%H:%M")) is.na(as.POSIXlt("26-Mar-1984-02:00",format = "%d-%b-%Y-%H:%M")) returns TRUE, FALSE, FALSE,...

How to Detect a Spurious Wakeup

java,linux,multithreading,pthreads,posix
I have read many posts on this. This answer http://stackoverflow.com/a/6701060/2359945 claimed a 100 bounty by suggesting to test the interrupted flag. I tested this, and it does not work for me. So, the question remains, how do I detect a spurious wakeup, or is it not possible? Thank you. class...

Unexpected nohup behaviour

unix,posix,nohup
I have an executable file test, it contains a="$RANDOM" echo "$a">>out Now, if I simply ./test then out contains a random number. But if I nohup ./test & then out is empty. Why?...

Understanding posix barrier mechanism

c,multithreading,pthreads,posix
Here is piece (very simplified, with global var's and other "smells") of C code, which uses posix barrier primitive to sincronize thread start. #include <pthread.h> #include <stdio.h> pthread_barrier_t barrier; void* thread_func(void* aArgs) { pthread_barrier_wait(&barrier); printf("Entering thread %p\n", (void*)pthread_self()); int i; for(i = 0 ; i < 5; i++) printf("val is...

How to conceal a segmentation fault in a bash script

osx,bash,segmentation-fault,posix,stderr
I use a program that works properly and results in desirable output at the end of its operation with no memory leak or any other specific issue, but then it issues a segmentation fault at the point it exits. I have been trying to hide this harmless but annoying error...

Open system call is not working as expected

c,linux,posix
I am trying out this code below. #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd; char filename[10]; printf("enter the file name\n"); scanf("%s",filename); fd=open(filename,O_RDONLY|O_CREAT|O_TRUNC,S_IRUSR); if(fd==-1) { printf("error opening file\n"); } else { printf("file opened successfully\n"); } return 0; } Here,I am settings file's permission such that only user can read...

How to determine logfile folder on Linux?

linux,posix,logfiles
I want to write a logfile of activities of my program. Does it always go to /var/log/ or /var/log/appname/ if multiple files are written? Is there a common environment variable like $LOGDIR? What would be the POSIX way to do that? Also, what is the expected log filename on *nix?...

Process Emulation

windows,fork,posix,simulation,createprocess
I want to simulate a video process, but I have no much clue about it as the code of process simulation is done by using fork() (POSIX), but now I am going to do it in Windows. Is it ok to use createProcess() ? I just needs some sort of...

Race condition with setpgid

c,linux,posix,pid,forking
While working on a program for my OS class, I discovered an interesting case involving a what appears to be a race condition involving setpgid. Compile each program below separately. After executing ./test 3 (or any number > 2), ps jx will show that all of the infy processes have...

Assure the execution of every thread

c,multithreading,pthreads,posix,pthread-join
I want to run 4 different threads calling the same method, and I want to make sure that every single run comes from a different running thread. With the code provided bellow, the method function is ran the expected number of times but it is always done by the same...

Is it possible to use a shared object constructor for setting the library search path?

c,shared-libraries,posix
I am storing shared objects in a hierarchical folder structure. Shared libraries can depend on one another. At runtime, shared library X may need to load shared library Y. I am unsure what mechanism I can use to have library X locate Y. I'd rather not use -rpath because it...