Text file busy linux ошибка

Minimal runnable C POSIX reproduction example

I recommend understanding the underlying API to better see what is going on.

sleep.c

#define _XOPEN_SOURCE 700
#include <unistd.h>

int main(void) {
    sleep(10000);
}

busy.c

#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(void) {
    int ret = open("sleep.out", O_WRONLY|O_TRUNC);
    assert(errno == ETXTBSY);
    perror("");
    assert(ret == -1);
}

Compile and run:

gcc -std=c99 -o sleep.out ./sleep.c
gcc -std=c99 -o busy.out ./busy.c
./sleep.out &
./busy.out 

busy.out passes the asserts, and perror outputs:

Text file busy

so we deduce that the message is hardcoded in glibc itself.

Alternatively:

echo asdf > sleep.out

makes Bash output:

-bash: sleep.out: Text file busy

For a more complex application, you can also observe it with strace:

strace ./busy.out

which contains:

openat(AT_FDCWD, "sleep.out", O_WRONLY) = -1 ETXTBSY (Text file busy)

Tested on Ubuntu 18.04, Linux kernel 4.15.0.

The error does not happen if you unlink first

notbusy.c

#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void) {
    assert(unlink("sleep.out") == 0);
    assert(open("sleep.out", O_WRONLY|O_CREAT) != -1);
}

Then compile and run analogously to the above, and those asserts pass.

This explains why it works for certain programs but not others. E.g. if you do:

gcc -std=c99 -o sleep.out ./sleep.c
./sleep.out &
gcc -std=c99 -o sleep.out ./sleep.c

that does not generate an error, even though the second gcc call is writing to sleep.out.

A quick strace shows that GCC first unlinks before writing:

 strace -f gcc -std=c99 -o sleep.out ./sleep.c |& grep sleep.out

contains:

[pid  3992] unlink("sleep.out")         = 0
[pid  3992] openat(AT_FDCWD, "sleep.out", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3

The reason it does not fail is that when you unlink and re-write the file, it creates a new inode, and keeps a temporary dangling inode for the running executable file.

But if you just write without unlink, then it tries to write to the same protected inode as the running executable.

POSIX 7 open()

http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html

[ETXTBSY]

The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR.

man 2 open

ETXTBSY

pathname refers to an executable image which is currently being executed and write access was requested.

glibc source

A quick grep on 2.30 gives:

sysdeps/gnu/errlist.c:299:    [ERR_REMAP (ETXTBSY)] = N_("Text file busy"),
sysdeps/mach/hurd/bits/errno.h:62:  ETXTBSY                        = 0x4000001a,        /* Text file busy */

and a manual hit in manual/errno.texi:

@deftypevr Macro int ETXTBSY
@standards{BSD, errno.h}
@errno{ETXTBSY, 26, Text file busy}
An attempt to execute a file that is currently open for writing, or
write to a file that is currently being executed.  Often using a
debugger to run a program is considered having it open for writing and
will cause this error.  (The name stands for ``text file busy''.)  This
is not an error on @gnuhurdsystems{}; the text is copied as necessary.
@end deftypevr

When I make a simple script, I get «Text File Busy» when I try to run it.

dbell@det-ui-supergbe:~$ cat > test2
ls
^Z
[2]+  Stopped                 cat > test2
dbell@det-ui-supergbe:~$ chmod a+x test2
dbell@det-ui-supergbe:~$ ./test2
-bash: ./test2: Text file busy

asked Nov 16, 2012 at 17:27

user1689961's user avatar

By hitting Ctrl-Z you suspended the cat, therefore the file is still open and being written to «in the background».

I suspect you want Ctrl-D for ‘end of file’.

It’s true that Ctrl-Z can mean ‘EOF’, but in this case, because you’re in a terminal that supports background tasks, Ctrl-Z means ‘suspend’.

Try this link for more information.

Ben Cox's user avatar

answered Nov 16, 2012 at 17:34

coteyr's user avatar

coteyrcoteyr

17.7k6 gold badges29 silver badges57 bronze badges

Почему когда на работающе системе я создаю какой нить скрипт на sh или bash, и пытаюсь его запустить то всегда вылазиет вот такая ошибка:

[root@server cron.hourly]# ./del-empty-rec
bash: ./del-empty-rec: /bin/sh: плохой интерпретатор: Текстовый файл занят

помогает только перезагрузка системы.


Записан


А если указать /bin/bash ?


Записан

Андрей Черепанов (cas@)



Записан


А сам скрипт нигде не открыт?


Записан

Андрей Черепанов (cas@)


Почему когда на работающе системе я создаю какой нить скрипт на sh или bash, и пытаюсь его запустить то всегда вылазиет вот такая ошибка:[root@server cron.hourly]# ./del-empty-rec
bash: ./del-empty-rec: /bin/sh: плохой интерпретатор: Текстовый файл занят

помогает только перезагрузка системы.

cat del-empty-rec ответит на этот вопрос.


Записан


#!/bin/sh

find /var/spool/asterisk/monitor/ -size -60c -delete


Записан



Записан


Что-то мне подсказывает, что концы строк в этом del-empty-rec не юниксовые, а досовские.


Записан

Если я попался вам навстречу, Значит вам со мной не по пути.
(С) Воскресение


Что-то мне подсказывает, что концы строк в этом del-empty-rec не юниксовые, а досовские.

Об этом говорит чуть ли не каждая вторая ссылка в поиске гугла.
Правда есть и другие моменты, но это надо на месте смотреть.
Включая через hexviewer:
CR, CR+LF, LF
Это базовый момент, который написан на платформе спектрум на каждом втором заборе.


Записан


Что-то мне подсказывает, что концы строк в этом del-empty-rec не юниксовые, а досовские.

Что, скрипты пишут под виндой ? реально ?


Записан


Что-то мне подсказывает, что концы строк в этом del-empty-rec не юниксовые, а досовские.

Что, скрипты пишут под виндой ? реально ?

извращенцев хватает…

——-
— Я слышал, что ездовые собаки бывают, но чтоб ездовые коты!..
— Ничего, на наших дорогах даже ездовые академики встречаются!
(Трое из Простоквашино)


Записан

Если я попался вам навстречу, Значит вам со мной не по пути.
(С) Воскресение


прочем тут переносы строк????
я же говорю что если систему ребутнуть или подождать сутки то скрипт начинает нормально работать.


Записан


« Последнее редактирование: 25.06.2014 19:47:56 от Speccyfighter »


Записан


прочем тут переносы строк????
я же говорю что если систему ребутнуть или подождать сутки то скрипт начинает нормально работать.

попробуйте lsof <путь к скрипту>

информация должна помочь.


Записан


Turn off and delete the swapfile.

Linux 5.x introduced official swapfile support for Btrfs. Unfortunately, this support appears to be, ahem, incomplete. I suppose what is happening is that a subvolume which contains an open non-COW file cannot be snapshotted (snapshot? snapfleshwounded?). On some level this makes complete sense. On another, wtf. sigh.

If you want to use a swapfile, I think it should be fine to create a separate subvolume, however I have not tested this. Otherwise, you really do need to delete the swapfile before making the snapshot otherwise the file will get reflinked, stop being non-COW even though you marked it as such, and swapon won’t work.

bash: ./myscript: /usr/bin/env: bad interpreter: Text file busy

«myscript» begins with #!/usr/bin/env python. Just retrying starting it fixed the problem.

Why system program env sporadically becomes «busy»? Can it be caused by prelink (but cron should start it not at that time…)

asked May 9, 2012 at 9:48

Vi.'s user avatar

4

Commenters say that it is script busy, not env or python and is caused by text editor saving it.

answered May 10, 2012 at 15:11

Vi.'s user avatar

Vi.Vi.

16.6k31 gold badges110 silver badges188 bronze badges

Usualy it’s «./myscript» witch is busy because another program modify the file. It can be a text editor (when save it) but also a remote copy (This can be long if the download rate is low) or another program.

answered Mar 25, 2014 at 9:24

user310345's user avatar

Понравилась статья? Поделить с друзьями:
  • Terraria error ошибка при запуске что делать
  • Terrain response range rover ошибка
  • Terrain response freelander 2 ошибка
  • Termokraft pk 24bt ошибка е7
  • Terminator win64 shipping системная ошибка