c,database,connection,posix,daemon
Signals interrupt process execution; they do not execute in parallel. So if there is only a single thread in the process, it will be suspended while the signal handler is executing. (If the process is multithreaded, only one thread will be interrupted and the others will continue executing.) However, there...
I suppose the question amounts to what network entries are good for. For the most part, they are used for routing. For instance, you should expect to see one or more of the functions in question being used by the route(8) and netstat(8) programs. Inasmuch as most hosts do not...
I figured out how to do what I needed to do. (Didn't exactly need to set the EOF indicator, but just needed to increase the position so cat did not endlessly read from my procfile.) The loff_t *data argument should actually be named offset or position. (I think this fits...
I ran into this problem myself when trying to port a library I was working on to OS X. I searched for a while without finding a great answer. When I did find the answer, I was a bit perturbed: the answer is effectively "if Apple implemented POSIX unnamed semaphores,...
c++,multithreading,pthreads,posix,producer-consumer
The author mentionned at the end of its article under Semantics of wait() and notify() that notify(cv) wakes up all threads that are currently waiting on that cv So your understanding of wait is incorrect, notify is meant to be pthread_cond_broadcast in posix. Furthermore the documentation of pthread_cond_signal stipulates The...
osx,bash,segmentation-fault,posix,stderr
From the Bad Idea Department: program options >file 2>/dev/null | cat It seems that bash won’t complain about segmentation faults in programs whose output is piped elsewhere. So just pipe your output anywhere. cat is a good choice, since it just echos the text it was sent. Or pipe to...
This call ... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR,0664, &attr); specifies too many parameters. The mode seems to have been specified twice. It should be ... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR, &attr); or ... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, 0664, &attr); Regarding EINVAL, the man mq_open states: EINVAL...
It's really simple void dir(DIR *f, char *file_name, char *dir_name) { struct dirent *a; int n = 0; while ((a = readdir(f)) != NULL) { if (strcmp(a->d_name,".") != 0 && strcmp(a->d_name,"..") != 0 && a->d_type == 4) { char s1[250]; DIR *next; strcpy(s1, dir_name); if (s1[strlen(s1) - 1] != '/')...
The sem_t itself must be in shared memory if it is to be "pshared". struct my_shared_mem { sem_t sem; int value; }; ... later ... struct my_shared_mem *shared; shmID = shmget(IPC_PRIVATE, sizeof(*shared), ...); shared = shmat(shmID, ...); shared->value = 0; sem_init(&shared->sem, 1, 1); ... ...
You can look at the implementation source code for details (the pthread implementation from the GNU libc Git repository can be browsed here), but they have different IDs that are used internally. You can see this at the application level using pthread_self(). It returns a pthread_t value that is unique...
The problem is due to the following difference in /usr/include/asm-generic/socket.h The socket.h in question is part of the linux-libc-dev package. In Debian, socket.h is from version 3.2.65 of linux-libc-dev, and contains contains the commented line /* To add :#define SO_REUSEPORT 15 */ On Ubuntu, linux-libc-dev is version 3.13.0. socket.h. Here,...
You have set -std=c11 -Wpedantic, which means that the normal defines are not available and POSIX function are not declared unless you explicitly set one of _POSIX_C_SOURCE or _XOPEN_SOURCE. Add #define _XOPEN_SOURCE 700 (or even 800 on Linux) before the first #include and all will be well. You have CPPFLAGS...
I suggest you to change the regex as, regex="value[[:space:]]*=([[:digit:].]+)>([[:alpha:][:space:]*/]+)" DEMO [[:digit:].] ^ ^ ^^^ | | |||-> end of char class start digit |-> DOT OR In pcre, the above would be written as [\d.]...
No it is not necessary. If you use ftruncate it is possible that the file is virtually constructed, means that blocks are reserved in the total allocated blocks count but not really allocated to the file (files can have holes relatively to their allocated blocks). In that case, block allocation...
This is not related to c++. Its for unix like operating systems. The ./ says look in the current directory for my script rather than looking at all the directories specified in $PATH ...
The easiest way for you to do this is by using the clock() function from <time.h> to report the amount of CPU time used by the calling process. From SUSv4: The clock() function shall return the implementation's best approximation to the processor time used by the process since the beginning...
Just check the filename before you print it. DIR *p; struct dirent *pp; p = opendir ("./"); if (p != NULL) { while ((pp = readdir (p))!=NULL) { int length = strlen(pp->d_name); if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0) { puts (pp->d_name); } } (void) closedir (p);...
c,arrays,struct,posix,shared-memory
You need to do this. Use shm_open in each process to get a file descriptor. You must pass shm_open the same name in each process. The name is what distinguishes the shared memory region from other shared memory regions. The name must begin with a slash: "/somename". Use the file...
bash,shell,posix,ksh,arithmetic-expressions
It's worse than you think. The value of the variable is recursively treated as an arithmetic expression: $ foo='bar+bar' $ echo $((foo)) 10 The bash manual section on Shell Arithmetic says: The value of a variable is evaluated as an arithmetic expression when it is referenced, or when a variable...
Measuring time is a complex problem. Generally the best way is to use clock_gettime(). It supports several clocks with different characteristics. Check this link for more information....
The problem is the particular combination of open flags. What you are saying is: Create this file it it doesn't exist (O_CREAT) Truncate it (O_TRUNC) Set its permissions to 0400 (S_IRUSR) The next time around when you try to open it, since it already exists open will just try to...
I think you're solving the problem other way round, unless you don't want to implement something like the Leader/Follower pattern, in which the threads take turns being leaders. This looks good on paper, but I've found it rarely to be efficient for ephemeral tasks due to the amount of locking...
You should pass the highest file descriptor value + 1, that's why n == 0 n = select( session_ref->fd, &fds, NULL, NULL, &timeout ); // n = 0 has to be n = select( 1 + session_ref->fd, &fds, NULL, NULL, &timeout ); // n = 0 and then check how...
Question 1: In the output below, echo "$a" is blank. Why? Because whitespace is special as defined in POSIX (2.6.5 Field Splitting): 3a. IFS white space shall be ignored at the beginning and end of the input. Question 2: And why does the output of echo $c does not contain...
c,sockets,network-programming,posix
recv(2) is a read operation, so sockfd should go in readfds instead of writefds. (Where's STDIN from by the way? On POSIX systems you can use STDIN_FILENO.) You already said this was simple test code (which is likely to work as expected in practice), but just in case you're not...
You shouldn't use sem_getvalue for this since you are losing atomicity. Use sem_trywait for the task for (;;) { if (sem_trywait(&sem1)) { if (errno != EAGAIN) { /* handle error */ abort(); } errno = 0; printf("do this\n"); } else { break; } } ...
sem = sem_open(name, O_CREAT , S_IRUSR | S_IWUSR, value); Will give read and write permissions. You can see the open(2) manual for other mode options: The following symbolic constants are provided for mode: S_IRWXU 00700 user (file owner) has read, write and execute permission S_IRUSR 00400 user has read permission...
Exact implementation is not guaranteed here but you can expect some properties. Usually sleep (3) is quite inaccurate and as Linux 'man sleep 3' states could be even implemented using SIGALM (signals). So it is definitely not about performance. It is definitely not about spin locks too so cannot be...
algorithm,filesystems,posix,atomic,compare-and-swap
Oh boy. Let's assume that each process has access to a unique identifier, to avoid problems breaking symmetry. Here's a wait-free implementation of a one-shot consensus object. Create a directory with a unique name. Create a file in that directory whose name is the creating process's input. Rename the directory...
This is the most convenient form I can come up with: some_chatty_cmd $( [ "$FLAG_VERBOSE" ] || echo --quiet ) arg... # default --quiet # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...
Change this flags O_WRONLY | O_RDONLY to O_RDWR check here, it says that the flags must include one of the access modes. Moreover, the ref mentions: The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read- only, write-only, or...
It looks like you are doing it to yourself. Consider this excerpt of the second code: user_sigval.sival_int = getppid(); sigqueue(pid, SIGRTMIN, user_sigval); Now look at the central part of the first code: sig=sigwaitinfo(&sigset, &siginfo); int pid = siginfo.si_value.sival_int; if (sig!=-1){ if (POcupadas != N){ ++POcupadas; user_sigval.sival_int = 0; sigqueue(pid, SIGRTMIN+1,...
Ignoring the fact that this is blatant undefined behavior, if you do an assignment of a global variable, the generated code is likely to use relative addressing to reference the variable on some architectures. That is, the function expects itself and x to be at a given address, and if...
Assuming you have a string that contains more than "one argument", you will first have to split the string (using a std::vector<std::string> would work to store the separate strings), then for each element in the vector, store the .c_str() of that string into a const char args[MAXARGS] [or a std::vector<const...
Transferring comment into an answer Are you on Ubuntu (or another Linux distro)? Is /bin/sh a link to /bin/dash rather than /bin/bash? If so, when you run it with bash as your shell, then $RANDOM works, but when nohup runs it with /bin/sh (aka dash), you get nothing. You might...
linux,file-io,path,posix,race-condition
No replies to this question, and I have spent several days trawling through Linux source code. I believe the answer is "currently you can't unlink a file race free", so I have opened a feature request at https://bugzilla.kernel.org/show_bug.cgi?id=93441 to have Linux extend unlinkat() with the AT_EMPTY_PATH Linux extension flag. If...
c,linux,bash,posix,post-increment
You seem to be seeking to find a defined standard for bash, as there is for C. Unfortunately, there isn't one. There are really only two guides: Volume 3 (Shell and Utilities) of the Open Group Base Specifications, commonly known as "Posix", which is deliberately underspecified. It does state that...
posix,interrupt,system-calls,avr,syscall
They don't. AVR has no provision for software interrupts. If you need to generate an interrupt from software then you will need to convince some piece of hardware to generate it instead. Otherwise just use a JSR as normal.
While you don't say what your timezone is, this looks like Daylight Saving Time (DST) issue. In timezones that use DST, there will be a day where the hour "jumps" from 1:59:59.999 to 3:00:00.000. This means that any times in the 2AM hour do not exist on this day. My...
c,linux,posix,standards,language-lawyer
As far as I can see, in C11 standard, there is no unistd.h and fcntl.h. So, strictly speaking, they are not part of the C standard. When it comes to the implementation part, the GNU C library (glibc) is one of them. From the wiki page glibc provides the functionality...
Does it always go to /var/log/ or /var/log/appname/ if multiple files are written? Absolutely not. Logs may not even be stored on the local system (they may be shipped off to a remote collector using any of a variety of technologies). Is there a common environment variable like $LOGDIR?...
linux,unix,awk,posix,separator
Here's a pragmatic summary that applies to all major Awk implementations: GNU Awk (gawk) - the default awk in some Linux distros Mawk (mawk) - the default awk in some Linux distros (e.g., Ubuntu) BSD Awk - a.k.a. BWK Awk - the default awk on BSD-like platforms, including OSX On...
If LC_ALL is set to collation order which differs from the ASCII byte-order default (LC_ALL=C), mkbuiltins can generate an array in builtins.c in which bsearch() can fail to find builtins. This is definitely a bug, and should be reported upstream....
I figured it out, finally. When setpgid failed, errno was set to EPERM. One of the possible errors on the man page for EPERM is: The value of the pgid argument is valid but does not match the process ID of the process indicated by the pid argument and there...
c++,linux,multithreading,process,posix
You're right, a blocking waitpid(m_pid, ...); m_pid = 0 in one thread of control and a kill(m_pid, ...) in another will race. Adding a mutex won't help for the reason you indicated — the waiter must wait and update some global information, but the killer must be allowed to (indirectly)...
No, you cannot in general. Some linkers might support it, but others definitely won't. Many dynamic linkers will just ignore changes to LD_LIBRARY_PATH or equivalent after the main executable is loaded, so you may not even be able to influence the loading path at all at runtime. Other linkers may...
c,multithreading,pthreads,posix,pthread-join
The reason you always see the same value You are printing your pointer as a integer. data points to your variable i in your main. The address of i will not change, hence the same value being printed. Printing the value of i What you want to do is dereference...
c++,gcc,visual-studio-2013,mingw,posix
Yeah, I tried the VisualGDB extension and it pretty much solves all the issues. MSVC and MinGW hate the crap out of each other and I really couldn't do much about it.
Since you have multiple threads contending for slots of the semaphore (else you wouldn't need semaphores at all), you need to protect against deadlock. For example, if your semaphore has four slots, and each of two threads is trying to acquire three, then they will deadlock if each manages to...
sockets,unix,pipe,posix,blocking
Unless you wish to send one byte at a time whenever select() says the fd is ready for writes, there is really no way to know how much you will be able to send and even then it is theoretically possible (at least in the documentation, if not in the...
c,multithreading,unix,signals,posix
"Random thread" doesn't means that it is delivered to a thread chosen at random, but that it can be delivered to any thread the implementers want. So random choice is a possibility, but any other choice is possible. On your system the choice is: the main thread first if possible....
Fixing the << 'EOF' heredoc direction would take some sh -c trickery that ended up causing even more problems, so I tried re-approaching the problem without requiring heredocs at all. I ended up landing on: inline() { # Ensure a file was provided in="${1?No input file specified}" # Create a...
I thought about it, tried it out, but in time find the solution. for(loop = i; loop >= start; loop--) { // change loop > start to >= if(/*(counter == 0) &&*/ (buffer[loop] == 10)) { and: if(i > start) { counter = 0; for(loop = i-1; loop > start;...
multithreading,synchronization,pthreads,posix,rwlock
You need some variable that stores the state. You can protect that variable with a lock. So when a thread needs to check or change the state, it acquires the lock, checks or changes the state, and then releases the lock.
c,sockets,posix,standard-library
The C programming language is and will likely always be a lightweight one. You need to understand that C runs basically anywhere and some things need a long research and work to get standardized. Also, I have seen that new libraries are added because C++ went ahead and made them...
In Signal handler there are only a very limited number of syscalls allowed. see man 7 signal http://man7.org/linux/man-pages/man7/signal.7.html My Suggestion is, to be on the safe side, the so called "self pipe trick". http://man7.org/tlpi/code/online/diff/altio/self_pipe.c.html You could start a thread which runs a select Loop on the self pipe and call...
The shmat calls only gets a pointer to a shared memory segment that should have previously be created with shmget. You have 2 ways to deal with that : allocate a segment that will hold an array for all your structs and then copy your structs to this array :...
If you can use negative lookahead you can use card((?!port).)*port to match a string with card, than any number of characters not followed by port, then card again. EDIT: if the input is always in the same format, then you can be more specific by using card[0-9]{1,2}_port. This will keep...
For the C++11 way, check the answer of bames53. This gives the time in nanoseconds. In Ubuntu, C++, you need to add -lrt to the list of libraries you link to. Example (in a mainfile): mm: main.cpp memory_manager.cc g++ -Wextra -Wall -Wreorder -o mm main.cpp memory_manager.cc -lrt #include <cstdint> //...
c,multithreading,pthreads,posix
What your barrier is doing is preventing Thread 1 from producing any output before Thread 2 is created. After both threads are created, both cross the barrier and are unblocked. After that you are not asserting any control as to how they are interleaved. So, thread 1 happens to get...
No. Just because EFAULT is the only errno listed, it doesn't mean uname will never fail as long as you pass a valid buffer. It could fail for any other reason. i.e. if uname's return code is -1, then it failed irrespective of the value of errno. errno is only...
No. In between the time when you use mkstemp() to create the file and the time when you reopen it, your adversary may have removed the file you created and put a symlink in its place pointing to somewhere else altogether. This is a TOCTOU — Time of Check, Time...
Your consumer works fine. It's just not flushing to stdout. Do as nos suggested by putting a \n at the end of your consumer printf call. You can also see it working by just waiting longer. Your producer will start producing again after the consumer has executed a few iterations.
I suppose this is a job for select(2), but constructing the fd_sets for the C arguments seems rather hairy. I suppose poll(2) should be more convenient. For example: #![feature(std_misc, net, libc, os, io)] extern crate libc; use libc::{c_int, c_uint, c_short}; use std::thread::spawn; use std::net::{TcpListener, TcpStream}; use std::os; use std::io::Read;...
You can try with difftime df1$time.diff <- with(df1, difftime(time.stamp2, time.stamp1, unit='min')) df1 # time.stamp1 time.stamp2 time.diff #1 2015-01-05 15:00:00 2015-01-05 16:00:00 60 mins #2 2015-01-05 16:00:00 2015-01-05 17:00:00 60 mins #3 2015-01-05 18:00:00 2015-01-05 20:00:00 120 mins #4 2015-01-05 19:00:00 2015-01-05 20:00:00 60 mins #5 2015-01-05 20:00:00 2015-01-05 22:00:00 120...
c,multithreading,thread-safety,posix,shared-libraries
You aren't using anything but automatic variables in your code, and the only function-call (clock_gettime) is inherently thread-safe, so the answer is: Yes, it's safe. From the POSIX spec: 3.396 Thread-Safe A function that may be safely invoked concurrently by multiple threads. Each function defined in the System Interfaces volume...
wc stops when there isn't any more input. So even if the child finished writing to the pipe, the parent waits for more input from itself because p[1] on it's side isn't closed. So by closing p[1], the parent process expresses it's intent that isn't going to provide input to...
c,pipe,multiprocessing,fork,posix
You're write logic is questionable, and the layout of your pipes is overtly complicated. Below is your code tailored down to as simple a case as I can muster. Comments are included to help yo along. I find it easiest when dealing with chained pipes (which is for all intents...
c++,osx,unix,serial-port,posix
I believe that you are correct when you say: It seems to me that as soon as read() gets a single byte, then it disregards VTIME. Return value for read(): On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced...
windows,fork,posix,simulation,createprocess
In Windows, you simulate fork with CreateThread, unless it's followed by exec, in which case you ues CreateProcess. The fork system call creates a clone of your process. The exec system call loads a new program into your process, replacing the old program....
Yes, temp_uart_count will contain the actual number of bytes read, and obviously that number will be smaller or equal to the number of elements of temp_uart_data. If you get 0, it means that the end of file (or an equivalent condition) has been reached and there is nothing else to...
The t flag is called a sticky bit. A sticky bit is a permission bit that is set on a directory that allows only the owner of the file within that directory or the root user to delete or rename the file. No other user has the needed privileges to...
From linux man pages read(2) manual: RETURN VALUE On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen...
linux,shared-libraries,posix,qnx
I can't find "Shared objects still referenced" error message in Linux or in opensource libraries. This message only mentioned in context of QNX. This QT patch https://qt.gitorious.org/qt/qtbase/commit/4af257eb3cfeef93adefda5f981742ffb58ba0ad says that this error is informative and can be ignored On QNX that's only "informative" Shared objects still referenced" dlerror should actually be...
Just do the project in Ubuntu. You're going to have a hard enough time learning about signals and process handling without having to worry about various differences between Cygwin and actual unix/linux. Another option is to install virtualbox and run Ubuntu within that. There should be no differences there. https://www.virtualbox.org/wiki/Downloads...
Converting between integer types is guaranteed to be "correct". That is, if the value being converted (regardless of its type) is representable in the converted-to type, the result will be that same value. In the first case, -10 is representable as an int32_t, so b will end up holding the...
does read() add a '\0'? No, it doesn't. It just reads. From read()'s documentation: The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. Is there potential for error here, other than the...
GNU libc (glibc) is too big and complicated for mobile phones, so Android implements its own special version of libc which is Bionic libc, which itself does not fully support POSIX , one of the most lacking features in the android Bionic libc is pthread_cancel() so if you don't use...
linux,pthreads,posix,scheduling
pthread_setschedparam() sets both the scheduler policy and scheduler parameters for an existing thread. pthread_attr_setschedparam() and pthread_attr_setschedpolicy() set the scheduler parameters and scheduler policy respectively for a thread attributes object (type pthread_attr_t). This will set the scheduler parameters and scheduler policy for any new threads that are then created using that...
c,networking,dns,posix,gethostbyname
If you cannot change the system configuration, you're pretty much condemned to implementing your own DNS resolver within your application. You could base your code on ADNS, or on the DNS resolver included in Polipo
As the other answer indicates, your original problem is that you're returning the float itself (x) when you should be returning a pointer to it. As for your comment about getting the return value with pthread_join(), note its prototype: int pthread_join(pthread_t thread, void **retval); It takes a pointer to a...
java,linux,multithreading,pthreads,posix
What spurious wakeups are not sleep() is not subject to spurious wakeups. The low-level system call it uses to sleep may be, but Java takes care of this detail for you, re-entering the system call if it's woken up prematurely. As a user you are not exposed to spurious wakeups....
c,multithreading,posix,destroy,readwritelock
You should implement a "disposed" state of your ReadWriteLock instance (the "active" field looks appropriate, but you don't use it, why?). Check it twice in rwl_writeLock / rwl_readLock, before and after the sem_wait() call. This trick is well-known as a "double-checking lock pattern". If you find your Lock to be...
POSIX requires certain functions to be a cancellation point and says cancellation points may occur in certain functions (optional cancellation points). You can read the entire list of mandatory and optional cancellation points from the manual pthreads(7): Cancellation points POSIX.1 specifies that certain functions must, and certain other functions may,...
It is safe. The $A variable will be expanded once before the for-loop starts executing: for i in foo bar baz Once that happens, any changes to IFS will have no effect. Refs: http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06 http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_05 If you are using IFS just to parse that string, you could do this: oldIFS=$IFS...
multithreading,synchronization,posix,semaphore
Yes, they synchronize threads. The Open Group Base Specification Issue 7 clarifies under General Concepts that all semaphores synchronize threads, whether they are POSIX-style (<semaphore.h>) or SysV-style (<sys/sem.h>): [T]the semaphore lock operation shall cause the calling thread to be blocked and added to the set of threads awaiting the semaphore...
From the kill(1p) man page: SYNOPSIS kill -s signal_name pid ... kill -l [exit_status] kill [-signal_name] pid ... kill [-signal_number] pid ... ... -signal_number Specify a non-negative decimal integer, signal_number, repre‐ senting the signal to be used instead of SIGTERM, as the sig argument in the effective call to kill()....
Problem solved. I was setting int sem_init(sem_t *sem, int pshared, unsigned int value); I was setting pshared value to 0 but: The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes. If pshared has the value 0, then the semaphore...