silverbullettt
silverbullettt

Reputation: 868

Is linux release the spinlock/semaphore when it kill a process?

If a process holds some spinlocks or semaphores, and exit accidently(e.g., killed by linux), would linux release these locks correctly? If linux doesn't do this work, why?

Upvotes: 9

Views: 5672

Answers (1)

bdonlan
bdonlan

Reputation: 231193

It depends on the type of lock you're talking about.

If you're talking about any kind of kernel internal lock, they will be released as appropriate (as your system would soon crash otherwise). In general these kind of locks are not owned by the process itself, but rather by some internal kernel workflow, and usually don't remain locked after the process returns to userspace anyway.

Note, however, that if the kernel is already deadlocked when you issue the kill, chances are the process won't be killed. Process killing is performed as part of the signal handling path, which is invoked from the kernel-to-userspace return transition code. If the process is waiting for a kernel spinlock, you'll never make it to the return code and so the process won't exit.

Additionally, if the process is killed because of a kernel OOPS, then all bets are off - the kernel is already in an inconsistent state, and the OOPS exit code doesn't try very hard to clean up any locks the kernel thread may have been holding at the time.

If you're talking about any sort of userspace spinlock or semaphore (including the sem_* family of IPC semaphores), no, they will not be released, as there is no concept of lock ownership with a semaphore.

If you're talking about the flock family of file locks, or fcntl(F_SETLK, ...) advisory locks, they will be automatically released when any file descriptor bound to the file in that process is closed. Because of this, flock is a bad idea to use in most cases, but yes, it would be released if the process was killed.

If you're talking about a process-local pthread_mutex, it's moot because the mutex will cease to exist along with the process.

If you're talking about a shared pthread_mutex in a shared memory segment (one in which pthread_mutexattr_setpshared has been used to make it sharable), it will be autoreleased only if it is also marked as a robust mutex, with pthread_mutexattr_setrobust - but it must be marked consistent before re-use; see the pthread_mutex_consistent manpage for details.

Upvotes: 11

Related Questions