How to make root-created files accessible to normal users? My device is running Android 8.0, rooted using Magisk as the su manager. I log into it using SimpleSSHD.

I'm trying to do some actions which require root access, and in the process I'm creating some files to be later used by normal users. But for some reason what I'm used to in "classical" Linux distributions doesn't appear to work: root-created files can't be read by normal users, whatever chown/chgrp/chmod actions I try. See the following session:

$ su -c "echo hello &gt; file.txt; chown $(whoami) file.txt; chgrp $(whoami) file.txt; chmod a+r file.txt"
$ cat file.txt
cat: file.txt: Permission denied
$ echo readable &gt; my.txt
$ su -c 'cp -a my.txt my-copy.txt'
$ cat my-copy.txt
cat: my-copy.txt: Permission denied
$ ls -l *.txt
-rw-r--r-- 1 u0_a182 u0_a182 6 2018-08-20 15:21 file.txt
-rw------- 1 u0_a182 u0_a182 9 2018-08-20 15:23 my-copy.txt
-rw------- 1 u0_a182 u0_a182 9 2018-08-20 15:22 my.txt
$ whoami
u0_a182


What's happening here? Why are permission bits, owner and group ignored for files I created as root? How to properly change owner to normal user?
Android uses SELinux to manage file access. The files created by root and non-root users differ by SELinux context:

$ ls -lZ *.txt
-rw-r--r-- 1 u0_a182 u0_a182 u:object_r:app_data_file:s0           6 2018-08-20 16:01 file.txt
-rw------- 1 u0_a182 u0_a182 u:object_r:app_data_file:s0           9 2018-08-20 16:01 my-copy.txt
-rw------- 1 u0_a182 u0_a182 u:object_r:app_data_file:s0:c512,c768 9 2018-08-20 16:01 my.txt


To make the file really belong to the non-root user, one has to set the correct SELinux context:

$ su -c 'chcon u:object_r:app_data_file:s0:c512,c768 file.txt'
$ cat file.txt
hello