我安装了 Arch Arm到 Rpi3 上,然后将 sysroot rsync 到安装在 Lenovo thinkpad 上的 x86_64 Arch Linux。
然后我安装了 arm-linux-gnueabihf Linaro交叉编译器
为了避免任何问题,我在编译中使用了绝对路径:
/home/sameh/Rpi/Compiler/gcc-linaro-7.2.1-2017.11-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf-gcc\
--sysroot=/home/sameh/Rpi/Arch/ArmV7/root\
-o stress stress.c -lm
代码编译正常,但是当我在 Rpi3 上执行它时没有输出。
它不会卡住 Pi,我可以ps aux
并查看由 fork()
创建的子进程。
但是没有打印任何调试语句,也没有任何进程退出。
编辑
此代码基于 stress图书馆。对于 MCVE,我将其最小化为只有 hogcpu
函数
#include <ctype.h>
#include <errno.h>
#include <libgen.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
int hogcpu (void);
int
hogcpu (void)
{
for(int i=0; i < 1000000; i++)
sqrt (rand ());
return 0;
}
int main()
{
struct timespec start, end;
double cpu_time_used;
int pid, children = 0, retval = 0;
long forks;
int do_dryrun = 0;
long long do_backoff = 3000;
long long do_cpu = 1;
long long backoff, timeout = 0;
/* Calculate the backoff value so we get good fork throughput. */
backoff = do_backoff * forks;
clock_gettime(CLOCK_REALTIME, &start);
while ((forks = (do_cpu + do_io + do_vm + do_hdd)))
{
if (do_cpu)
{
switch (pid = fork ())
{
case 0: /* child */
alarm (timeout);
usleep (backoff);
exit (hogcpu ());
case -1: /* error */
break;
default:
++children;
}
--do_cpu;
}
}
/* Wait for our children to exit. */
while (children)
{
int status, ret;
if ((pid = wait (&status)) > 0)
{
--children;
if (WIFEXITED (status))
{
if ((ret = WEXITSTATUS (status)) == 0)
{
printf( "<-- worker %i returned normally\n", pid);
}
else
{
printf( "<-- worker %i returned error %i\n", pid, ret);
++retval;
printf( "now reaping child worker processes\n");
if (signal (SIGUSR1, SIG_IGN) == SIG_ERR)
printf( "handler error: %s\n", strerror (errno));
if (kill (-1 * getpid (), SIGUSR1) == -1)
printf( "kill error: %s\n", strerror (errno));
}
}
}
}
clock_gettime(CLOCK_REALTIME, &end);
cpu_time_used = (end.tv_nsec = start.tv_nsec) / 1000000000.0;
/* Print final status message. */
if (retval)
{
printf( "failed run completed in %.2f s\n", cpu_time_used);
}
else
{
printf( "successful run completed in -- %.2f s\n", cpu_time_used);
}
exit (retval);
}
我可以通过以下方式在 Pi 上成功编译和执行它:
[alarm@control ~]$ gcc stress.c -o stress -lm
[alarm@control ~]$ ./stress
<-- worker 16834 returned normally
<-- worker 16835 returned normally
<-- worker 16836 returned normally
successful run completed in -- 0.90 s
但是,当交叉编译并传输到 Pi 时,上述行为就是我所看到的。
注意
这很可能与 clock_gettime
调用有关。当我将其替换为 clock()
函数调用时,我可以在笔记本电脑上编译并运行它,但在 Pi 上使用 gcc
进行编译具有与上述相同的行为。
当使用 clock_gettime
并在 Pi 上编译时,它工作正常。
最佳答案
这里的问题是如何初始化 long forks;
变量。我不是很懂编译器,但是因为forks
没有初始化,计算backoff = do_backoff * forks;
结果是一个随机的负数。
这阻止了调用 usleep (backoff);
完成。所以将 forks
初始化为 1 解决了这个问题。
我原以为编译器应该将 forks
初始化为 0
作为 bss_data
的过去,所以我不确定为什么它没有。可能需要对该部分进行更多研究,但代码现在可以通过交叉编译正常执行。
关于Arch Arm 的交叉编译不会生成功能可执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029330/